$http get shortcut messing up program in AngularJS? - angularjs

In the script below, I have posted a boiled down version of my code. It's essentially a simplified search engine.
The script loops through the $scope.list_of_fruit array, and filters it according to what is typed on a simple html input text box.
<script>
var app = angular.module("myapp",[]);
app.controller("usercontroller", function($scope){
$http
.get("test.php")
.then(function (response) {
$scope.myData = response.data.records;
});
$scope.list_of_fruit = ["apple", "banana", "pear", "kiwi"];
$scope.complete = function(boxtext){
var output = [];
angular.forEach($scope.list_of_fruit, function(fruit){
if(fruit.toLowerCase().indexOf(boxtext.toLowerCase()) == 0)
{
output.push(fruit);
}
});
$scope.filteredfruit = output;
}
});
</script>
This works fine and dandy, but when I paste that http get request up top, that is completely unrelated to that $scope.complete loop, the $scope.complete loop just stops working.
Am I missing something obvious?

app.controller("usercontroller", function($scope){
You don't have $http defined, so you are probably getting an javascript error.
Add $http to the function parameters:
app.controller("usercontroller", function($scope, $http){
I created a snippet and this appears to work now
var app = angular.module('myApp', []);
app.controller("usercontroller", function($scope, $http){
$http
.get("https://jsonplaceholder.typicode.com/posts")
.then(function (response) {
$scope.myData = response.data.records;
});
$scope.list_of_fruit = ["apple", "banana", "pear", "kiwi"];
$scope.complete = function(boxtext){
console.log(boxtext);
var output = [];
angular.forEach($scope.list_of_fruit, function(fruit){
if(fruit.toLowerCase().indexOf(boxtext.toLowerCase()) == 0)
{
output.push(fruit);
}
});
$scope.filteredfruit = output;
}
});
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://rawgit.com/angular/bower-angular/master/angular.min.js"></script>
<div ng-controller="usercontroller as vm">
{{list_of_fruit}}
{{filteredfruit}}
<input type="text" ng-model="search"/>
<button ng-click="complete(search)">Do something</button>
</div>
</body>
</html>

Related

AngularJs dependency injection related to $http

While writing the above code in AngularJs, I am getting an error :
Error: $injector:unpr
Unknown Provider
Unknown provider: $http
I believe the reason might be while injecting $http through the serviceProvider which in my case is httpServiceProviderFunction.$inject = ["$http"];. I would appreciate if anyone could help me understand these two questions:
1) Although I have injected the $http in the httpServiceProviderFunction. Why am I getting the above error?
2)Is there any way I can inject $http in the service directly without injecting in serviceProvider? In my example, it corresponds to this line:
function httpService(url, $http) {.....}
The code snippet can be found below:
(function() {
angular.module("httpServiceApp", []).controller("httpServiceController", httpServiceControllerFunction).provider("httpService", httpServiceProviderFunction).config(configObj);
configObj.$inject = ["httpServiceProvider"]
function configObj(httpServiceProvider) {
httpServiceProvider.configuration.baseUrl = "http://davids-restaurant.herokuapp.com/categories.json";
}
httpServiceProviderFunction.$inject = ["$http"];
function httpServiceProviderFunction($http) {
var provider = this;
provider.configuration = {
baseUrl: "http://davids-restaurant.herokuapp.com/categories.json"
}
provider.$get = function() {
var service = new httpService(provider.configuration.baseUrl, $http);
return service;
}
}
function httpService(url, $http) {
var service = this;
service.menuCategories = function() {
var response = $http({
method: "GET",
url: url
});
return response;
}
}
httpServiceControllerFunction.$inject = ["httpService"]
function httpServiceControllerFunction(httpService) {
var service = httpService;
var controller = this;
var promise = service.menuCategories();
promise.then(function(response) {
controller.categories = response.data;
}).catch(function(error) {
console.log("Error occured", error);
})
}
})();
<!DOCTYPE html>
<html ng-app="httpServiceApp">
<head>
<meta charset="utf-8">
<meta name="description" content="First Angular App">
<meta name="keywords" content="HTML, Javascript, AngularJs">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
<script src="app1.js"></script>
<title>HTTP service in AngularJs</title>
</head>
<body>
<div ng-controller="httpServiceController as controller">
<div>
<ul>
<li ng-repeat="items in controller.categories">({{items.short_name}}){{items.name}}</li>
</ul>
</div>
</div>
</body>
</html>
Thank you for your time. I appreciate your help.

Pulled out all my hair on an Angular unpr error

So I am getting an angular [$injector:unpr] error. Yes, I know what that normally means...I haven't defined something somewhere, or I am redefining the module over and over, or the like...but for the life of me I'm struggling to see the issue in my code.
I'm sure I'm missing something insanely basic, but after I've stared at code for a couple of hours, I go blind to it.
My HTML File:
<!DOCTYPE html>
<html ng-app="email">
<head>
<meta charset="UTF-8">
<title>Authentication</title>
<link href='https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700' rel='stylesheet' type='text/css'/>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
</head>
<body>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="node_modules/angular/angular.min.js"></script>
<div ng-controller="EmailAuthController as auth">
<h1>Authentication</h1>
<p>Request: [{{auth.request}}]</p>
<p>{{auth.response}}</p>
<p>{{1+2}}</p>
</div>
<script type="text/javascript" src="js/controllers/email.js"></script>
</body>
</html>
My email.js file (As you can see, I've commented out some stuff to try to isolate the issue):
/* global angular parseGet */
function parseGet(val) {
var result = '', // = "Not found",
tmp = [];
var items = location.search.substr(1).split('&');
for (var index = 0; index < items.length; index++) {
tmp = items[index].split('=');
if (tmp[0] === val) {
result = decodeURIComponent(tmp[1]);
}
}
return result;
}
(function () {
angular
.module('email', [])
.controller('EmailAuthController', [ '$scope','authFactory', function ($scope,authFactory) {
var vm = this,
req = parseGet('hash') || '';
vm.request = req;
// authFactory.validate(req)
// .then(function (response) {
// vm.response = response.data;
// });
}])
.factory('authFactory', [ '$rootScope', '$http', 'config', function ($rootScope, $http, config) {
var validate = function (hash) {
var url = config.SERVICE_URI + '/auth/email/' + hash;
return $http.get(url);
};
return {
validate: validate
};
}]);
})();
From the code you've given it appears config is not defined in your authFactory injection.
.factory('authFactory', [ '$rootScope', '$http', 'config', function(a, b, c) {} ]); // config is not defined

Get JSON Response on HTTP GET in Angular

I create controller and html page And I want get http response with JSON string But I do not see nothing.
angular.module('myApp.view3', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view3', {
templateUrl: 'view3/view3.html',
controller: 'View3Ctrl'
});
}])
.controller('View3Ctrl',function($scope, $http) {
$scope.my_name = "Pasha";
$http({
method : "GET",
url : "http://api.geosvc.com/rest/US/84606/nearby?apikey=#APIKEY&d=20&pt=PostalCode&format=json"
}).then(function mySucces(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
It is my html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My view</title>
</head>
<body ng-controller="View3Ctrl">
<p> Hello Pavel</p>
<div>{{my_name}}</div>
<div>{{myWelcome}}</div>
</body>
</html>
And after load page I get this result
Hello Pavel
Pasha
Angular seed app: v0.1
But I want see JSON result too
Modify your html like this.
Here you are iteration over the whole data array and printing one bye one.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My view</title>
</head>
<body ng-app="myApp.view3" ng-controller="View3Ctrl">
<p> Hello Pavel</p>
<div ng-repeat="row in myWelcome">
<div>{{row.my_name}}</div>
<div>{{row.myWelcome}}</div>
</div>
</body>
</html>
copy the url service that u want to call on the browser then, see the JSON results. U will be see that the returned JSON didn't have a data object or status text object. That's mean u can print the JSON with this code:
angular.module('myApp.view3', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view3', {
templateUrl: 'view3/view3.html',
controller: 'View3Ctrl'
});
}])
.controller('View3Ctrl',function($scope, $http) {
$scope.my_name = "Pasha";
$http({
method : "GET",
url : "http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode&format=json"
}).then(function mySucces(response) {
$scope.myWelcome = response;
}, function myError(response) {
$scope.myWelcome = response;
});
});
app.js
var app = angular.module('angularTable', []);
app.controller('listdata',function($scope, $http)
{
$scope.users = []; //declare an empty array
$http.get("mockJson/mock.json").success(function(response)
{
$scope.users = response; //ajax request to fetch data into
});
});
index.html
<tr ng-repeat="user in users">
<td>{{user.id}}</td>
<td>{{user.first_name}}</td>
<td>{{user.last_name}}</td>
<td>{{user.hobby}}</td>
</tr>

Wait for async data before rendering a list on AngularJS and Ionic

I am a newbie on Angular JS but have good experience working with Javascript.
In my App I am creating a simple Factory fulfilled by JSON data coming from a web service:
.factory('Tools', function($http) {
var tools = {content:null};
var promise = $http.get('/Tool/GetTools').success(function(data) {
tools.content = data;
//At this points all the data is on tools.content
});
return {
promise:promise,
all: function(){
return tools;
//At this point tools equals to null
}
}
});
But when I want to render the list:
<ion-list>
<ion-item ng-repeat="tool in tools">
Hello, {{tool}}!
</ion-item>
</ion-list>
The info isn't still there yet.
I have this on my controller:
.controller('AccountCtrl', function($scope, Tools) {
$scope.tools = Tools.all();
});
Is there a way to tell the list to "wait" while the Tools object loads from the ajax call before the list renders?
Thanks!
You have to return from your factory the promise and into controller you can check the success.
Something like this:
(i've simulated the wait with a timeout)
angular.module('App', [])
.controller('Ctrl', function($scope, resultsFactory) {
$scope.results = [{txt: 'Loading..'}];
resultsFactory.all().then(
function(res){
$scope.results = res;
},
function(err){
console.error(err);
}
);
})
.factory('resultsFactory', function($http, $timeout, $q) {
var results = {};
function _all(){
var d = $q.defer();
$timeout(function(){
d.resolve([{txt:'one'},{txt:'two'},{txt:'three'}]);
}, 2000);
return d.promise;
}
results.all = _all;
return results;
});
<!DOCTYPE html>
<html ng-app='App'>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.20/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div ng-controller='Ctrl'>
<p ng-repeat='res in results'> {{res.txt}}</p>
</div>
</body>
</html>
You have to say {{tool}}
Its typo :-)
<ion-list>
<ion-item ng-repeat="tool in tools">
Hello, {{tool}}!
</ion-item>
</ion-list>

Use scope from multiple controllers on page

So i've split out my UI into subcomponents but then i realise that one of the components requires to be react to a dropdown change which is caught by the parent controller.
I can create a shared service for the variables and i have been able to inject the sub controller so that i can kick off functions BUT.
how do i then use the scope within the sub controller?
var ctrl1= $scope.$new();
$controller('ctrl', { $scope: ctrl1});
ctrl1.GetData();
this works fine. I can see data coming back in the console. BUT my ui doesnt change. What am i missing?
I've edited the post to illustrate what i'm attempting to do more clearly.
The drop down on change is caught by the parent controller but i then require the child controller to run away and get some data and update the UI.
It's an attempt to split out the components. Is this possible? Or have a split the components out too far?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<script>
angular.module('app2', [])
.controller('ctrl2', ['$scope', '$http', function($scope, $http){
$scope.getdata = function(){
$http.post(WebServiceURL)
.success(function(data){
$scope.app2Data = "test2 data";
});
}
}]);
angular.module('app1', ['app2'])
.controller('ctrl1', ['$scope','$controller',function($scope, $controller){
$scope.name = 'Controller 1';
//just something to put in the ddp
$scope.data = [
{id:1, name: "test"},
{id:2, name: "test2"}
]
$scope.makeChanged = function(id){
//ddp has changed so i refresh the ui with some other data which is in got by ctrl2.
var cl2 = $scope.$new();
$controller('ctrl2', { $scope: cl2 });
cl2.getdata();
}
}]);
</script>
</head>
<body ng-app="app1">
<div ng-controller="ctrl1">
<p>here is: {{name}}</p>
<select ng-model="d" ng-options="d as dat.name for dat in data track by dat.id" ng-change="makeChanged(d.id)"></select>
<div>
{{app2Data.text}}
</div>
</div>
</body>
</html>
for anyone interested here's how i got round this.
I created a shared service between the two controllers. and created a callback on the service. i registered the call back on ctrl2 so when the shared variable changed the controller2 will do what i want it to and scope is freshed.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<script>
angular.module('app1', ['app2'])
.controller('ctrl1', ['$scope', '$controller', 'appointmentSharedProperties',
function($scope, appointmentSharedProperties) {
$scope.name1 = 'Controller 1';
console.log('ctrl1');
//just something to put in the ddp
$scope.data = [{
id: 1,
name: 'test'
}, {
id: 2,
name: 'test2'
}];
$scope.makeChanged = function(value) {
//ddp has changed so i refresh the ui with some other data which is in got by ctrl2.
appointmentSharedProperties.setDetail(value);
console.log('in makeChanged: ' + value);
}
}
]).service('appointmentSharedProperties', function() {
var test = '';
var __callback = [];
return {
getDetail: function() {
return test;
},
setDetail: function(value) {
test = value;
if (__callback.length > 0) {
angular.forEach(__callback, function(callback) {
callback();
});
}
},
setCallback: function(callback) {
__callback.push(callback);
}
};
});
angular.module('app2', [])
.controller('ctrl2', ['$scope', 'appointmentSharedProperties',
function($scope, appointmentSharedProperties) {
$scope.name2 = 'Controller 2';
console.log('ctrl2');
var getdata = function() {
console.log('in getdata');
$scope.app2Data = appointmentSharedProperties.getDetail();
}
appointmentSharedProperties.setCallback(getdata);
}
]);
</script>
</head>
<body ng-app="app1">
<div ng-controller="ctrl1">
<p>here is: {{name1}}</p>
<p>here is: {{name2}}</p>
<select ng-model="d" ng-options="d as dat.name for dat in data track by dat.id" ng-change="makeChanged(d.name)"></select>
<div>
{{app2Data}}
</div>
</div>
</body>
</html>
General example of how to pass variables from one controller to other
<html>
<head>
<meta charset="ISO-8859-1">
<title>Basic Controller</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
</head>
<body ng-app="myApp">
<div ng-controller="ctrl1">
{{greeting}}
</div>
<div ng-controller="ctrl2">
{{dataToHtml2}}
</div>
</body>
</html>
This is the javascript file for this
var myApp = angular.module('myApp',[]);
myApp.service('sampleService', function(){
var temp = '';
this.setValue = function(data){
temp = data;
}
this.getValue = function(){
return temp;
}
});
myApp.controller('ctrl1', function($scope,sampleService) {
$scope.greeting = 'This line is in first controller but I exist in both';
var data= $scope.greeting;
sampleService.setValue(data);
});
myApp.controller('ctrl2', function($scope, sampleService){
$scope.dataToHtml2 =sampleService.getValue();
});
Here is the blog that explains this flow : Frequently asked questions in angularjs
It has the demo of what I written. Happy coding..!!

Resources