ajax call in a controller : $http is not defined - angularjs

I need a ajax call inside the function but if i use $http i am getting $http is not defined pls suggest me my code is
<script type="text/javascript">
function ContactController($scope) {
$scope.contacts = ["hi#email.com", "hello#email.com"];
$scope.add = function() {
alert("panduuuu")
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
$http.get('http://localhost:8080/ProjectManagement/REST/Login/Check?usename='+usename+'&password='+password+'')
.success(function(data, status, headers, config,response){
alert("insideee")
var json = JSON.stringify(data);
var getresponseText = JSON.parse(json);
var value=getresponseText.responseText;
}).error(function(data, status, headers, config,response) {
});
}
}
</script>

Correctly Passing Params
You should pass parameters to a http request like this
$http.get('http://MyServerIP:ServerPort/APICall', { params: { user_id: $scope._id } })
Also you should make calles like this in a service or a factory to be reused if needed
Add Your Correct Services
you also forgot to add $http in your function, next to $scope
ContactController($scope, $http)

You need to inject the $http service to your controller like this :
<script type="text/javascript">
function ContactController($scope, $http) {
...

You haven't injected the $http service into your controller.
angular.module('myApp', [])
.controller('ContactController', ['$scope', '$http', function ($scope, $http){
//awesome stuff
});
<div ng-app="myApp">
<div ng-controller="ContactController">
</div>
</div>
On a side note you should avoid registering controllers like you are and use .controller or .service etc. Also the array notation allows Angulars dependency system to work if you intend on minifying your JS.
https://docs.angularjs.org/guide/controller

Related

How to all data at once and apply to controllers in angularjs

i want to get all data at once through AJAX($http) request and apply to all controllers
i picked this code from google it shows the i have to make requests for each controller were i can get data in once ajax call and apply objects according to the controlers i have tried factory in angular but it did't work please help me to find out a way where i can get data at once and update all data in controllers
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
</script>
thank you.
As per your comment, this will work:
mainApp.controller('ABC',function($rootScope){
$scope.somethingHappened = function(){
$rootScope.$emit('valueChanged',your_data_to_be_passed)
}
})
mainApp.controller('DEF',function($rootScope){
$rootScope.$on('valueChanged',function(event,data){
console.log(data) // you'll see your_data_to_be_passed
})
})
Since, the controllers are not related, you should prefer $rootScope events rather than $scope.$broadcast or $scope.$emit. You can get more details about them on online tutorials
You may use $rootScope instead
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
<script>
var app = angular.module('myApp', []);
app.run(function($rootScope){
$http.get("welcome.htm")
.then(function(response) {
$rootScope.myWelcome = response.data;
});
})
app.controller('myCtrl', function($scope, $http) {
// Here watch for scope
$scope.$watch("myWelcome", function(value){
console.log(value)
})
});
</script>
You could use localStorage and use JSON(stringify and parse) methods if the data is not a string, if its object access to properties, if its array access to index.
<script>
var app = angular.module('myApp', []);
app.run(function($rootScope){
$http.get("welcome.htm")
.then(function(response) {
localStorage.setItem('data', JSON.stringify(response));
});
})
app.controller('anotherCtrl', function($scope, $http) {
$scope.myWelcome = JSON.parse(getItem('data'));
/*or you can do this
var full_data = JSON.parse(getItem('data'));
(object)$scope.myWelcome = full_data.[some_property];
(array of objects)$scope.myWelcome = full_data[index].[some_property];
(just array) $scope.myWelcome = full_data[index]
*/
});
</script>

Angular Service returning "undefined"

So I am sure I am not using best practices, but, I'm just trying to get this to work. I'm making a note taking app, and for whatever reason, the service I created, returns undefined and I can't figure out why.
Here's the service:
angular.module('notesService', []).factory('Notes', ['$http', function($http){
return {
get : function(){
var notes = $http.get('/api/notes');
return notes;
}
}
}]);
And here is the controller:
angular.module('mainController', [])
.controller('mainController', function($scope, Notes){
console.log(Notes.get());
});
The controller is not producing anything on the page just yet, i'm still testing.
Here is what the service returns to my controller:
e {
$$state : {
status : 1,
value : {
config : Object,
data: Array[10]
}
}
}
This isn't the entire thing, but it is all the stuff I need for my purposes.
Whenever I access $$state.value it returns undefined and I have no idea why.
You have the service in an entirely different module. So you gotta inject notesService into angular.module('mainController', [notesService]).
You dont ideally need to add new module for each controller and services, you can have single module and add everything to it
$http return a promise see documentation for $http
Also there is no need of the empty array in the angular.module parameter [] this might be what causes the error see in console.
angular.module('notesService').factory('Notes', ['$http', function($http){
return {
get : function(){
return $http.get('/api/notes');
}
}
}]);
angular.module('mainController')
.controller('mainController', function($scope, Notes){
Notes.get().then(function(result){
console.log(result);
})
});
I created an application that will help you to learn the best practices, plus solve your current problem.
//--In app.module.js--//
angular.module('notesApp', []);
//-- In app.controller.js--//
angular.module('notesApp')
.controller('MainController', ['$scope', '$http', '$log', 'notesFactory',
function($scope, $http, $log, notesFactory) {
$scope.data = {};
notesFactory.getData('http://localhost:3000/api/notes', 'GET')
.then(function(response) {
$log.log(response.data);
}, function(error) {
$scope.data = error;
});
}
]);
//--In app.service.js --//
angular.module('notesApp')
.factory('notesFactory', ['$http',
function($http) {
var notesService = {};
notesService.getData = function(url, method) {
return $http({
url: url,
method: method
});
}
return notesService;
}
]);
<html ng-app='notesApp'>
<head>
<title>
Notes Application
</title>
</head>
<body>
<div ng-controller='MainController'>
<pre>{{ data | json}}</pre>
</div>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js'></script>
<script src='app.module.js'></script>
<script src='app.controller.js'></script>
<script src='app.service.js'></script>
</body>
</html>
Check the console for the json object as shown in the screenshot

AngularJS Ctrl As Syntax with Services

I'm migrating my Angular 1.x code to use the newer, more preferred syntax of avoiding using $scope and using the controller as syntax. I'm having an issue with getting data from a service though.
Here's my example:
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$http', '$location', 'userService',
function($http, $location, userService) {
this.name = 'John Doe';
// this.userData = {
// }
this.userData = userService.async().then(function(d) {
return d;
});
console.log(this.userData);
}
]);
myApp.service('userService', function($http) {
var userService = {
async: function() {
// $http returns a promise, which has a then function, which also returns a promise
var promise = $http.get('https://jsonplaceholder.typicode.com/users').then(function(response) {
// The then function here is an opportunity to modify the response
// console.log(response);
// The return value gets picked up by the then in the controller.
return response.data;
});
// Return the promise to the controller
return promise;
}
};
return userService;
});
<body ng-app="myApp">
<div id="ctrl-as-exmpl" ng-controller="MainCtrl as mainctrl">
<h1>Phone Numbers for {{mainctrl.name}}</h1>
<button ng-click="">newest</button>
<p>{{mainctrl.userData}}</p>
<ul>
<li ng-repeat="users in mainctrl.userData">{{users.phone}} -- {{users.email}}</li>
</ul>
</div>
</body>
This issue I'm having is that the data returned from the userService.async is an object that I can't seem to drill down thru to get the data from, as the data is a child of $$state, which can't seem to be used in the view.
If this isn't the proper way to use services in the Controller As/$scope-less syntax, what is the proper way?
Live example here: http://plnkr.co/edit/ejHReaAIvVzlSExL5Elw?p=preview
You have a missed an important part of promises - when you return a value from a promise, you return a new promise that will resolve to this value.
The current way to set the data returned from a promise to a local variable in your controller is this:
myApp.controller('MainCtrl', ['$http', '$location', 'userService',
function($http, $location, userService) {
this.name = 'John Doe';
userService.async().then(function(d) {
this.userData = d;
});
}
]);
But now you are in a catch because of the scope of this, so it is common to use a "placeholder" variable for the controller this scope.
myApp.controller('MainCtrl', ['$http', '$location', 'userService',
function($http, $location, userService) {
var $ctrl = this; // Use $ctrl instead of this when you want to address the controller instance
$ctrl.name = 'John Doe';
userService.async().then(function(d) {
$ctrl.userData = d;
});
}
]);
this.userData = userService.async().then(function(d) {
return d;
});
In this bit of code this.userData is actually being defined as a promise. If you want the data that is being returned, you need to use the d parameter from your .then function like so:
userService.async().then(function(d){
this.userData = d;
//a console.log() here would determine if you are getting the data you want.
});
Edit
I just noticed in your Service that you are already using .data on your response object.
Honestly, my best advice to you would be to just return the promise from the http.get() call inside of your service like this:
myApp.service('userService', function($http) {
var userService = {
async: function() {
return $http.get('https://jsonplaceholder.typicode.com/users');
}
};
return userService;
});
And then you could use something like this to capture and utilize the response data:
userService.async().then(function(response){
this.userData = response.data;
);
This may be a bit cleaner of a solution

Updating the scope variable across multiple controllers in angularjs

I have two controllers- searchBoxController and productList. What I am trying to do is to update the scope variable $scope.products from multiple controllers. I know that defining it as a root variable is a very bad design- but putting that in shared service is not solving the problem. The update doesn't reflect in the HTML templates!
function SearchTermService(){
this.productSearch = function(data, $http){
var url = "";
$http.get(url).then(function(resp){
return resp.data;
},
function(err){
console.log(err);
});
};
};
var app = angular.module('app', []);
app.service("myService", MyService);
app.service("searchTermService", SearchTermService);
app.run(function($rootScope) {
$rootScope.products = new Date();
});
app.controller('productList', function ($scope, $rootScope, $http, myService) {
$rootScope.products = prod_res;
});
app.controller('searchBoxController', function($scope, $http, searchTermService, $rootScope){
$scope.getSearchResults = function(){
$rootScope.products = searchTermService.productSearch($scope.term, $http)
};
});
PS: I am not sure if I need to have a promise returned while assigning the $rootScope.products in 'searchBoxController', as the console.log says its undefined. Currently I am not returning a promise from the service.
In order to update a scope variable across multiple controller, you can use angular service.
You should use this because all angular services are singletons, so you can easily share common logic, share data between controller.
I've made an example where I use service in order to update some data. Then, my factory return an object data, so we will get an object, not just a fixed value. Thanks to this, our data will be updated, we will keep the binding data.
Controller
(function(){
function Controller($scope, $timeout, Service) {
//Retrieve current data object of our service
$scope.data = Service.value;
//will be set to 4
$timeout(function(){
Service.set(4, 'product');
}, 1000);
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
(function(){
function Controller2($scope, $timeout, Service) {
//Retrieve current data object of our service
$scope.data2 = Service.value;
}
angular
.module('app')
.controller('ctrl2', Controller2);
})();
Service
(function(){
function Service() {
//Our data object
var data = {
product: null
};
function set(value, field){
data[field] = value;
}
return {
set: set,
value: data
};
}
angular
.module('app')
.factory('Service', Service);
})();
HTML
<body ng-app='app'>
<div ng-controller='ctrl'>
<h2>Service value : {{data.product}}</h2>
</div>
<div ng-controller='ctrl2'>
<h2>Service value from controller2 : {{data2.product}}</h2>
</div>
</body>
So, we will share our data across multiple controller. By using services, you can avoid to use the $rootScope.
You can see the Working plunker

How can I make an HTTP request using Angular.js?

I'm trying to make an HTTP request to the Last.fm API using Angular.js but I can't get it to work. I have separated out my Angular js files and have compiled them into one single js file called scripts.js using Codekit. The order in which the files are compiled is:
angular.min.js
app.js
controllers.js
services.js
Here is what my files look like:
app.js
var app = angular.module('app', []);
controllers.js
app.controller('similarArtistsController', function($scope, similarArtistsService) {
$scope.artists = [];
similarArtistsService.getArtists().success(function(response) {
console.log(response);
});
});
services.js
app.factory('similarArtistsService', function($http) {
var similarArtists = {};
similarArtists.getArtists = function() {
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=artist.getSimilar&api_key=MYLASTFMAPIKEY&format=json&limit=5&artist=Tame+Impala'
});
}
return similarArtists;
});
index.html
<body>
<div ng-app="app">
<div ng-controller="similarArtistsController"></div>
</div>
<script src="/js/compiled/scripts.js"></script>
</body>
In my console I see "Error: [$injector:unpr]" which I've learned to mean that the controller cannot resolve a dependency. In my case I believe it has something to with my service I'm injecting, but I don't know where the error lies.
Does compiling the scripts minify them too? If so, you need to declare your dependencies in an array...
app.controller('similarArtistsController', ['$scope', 'similarArtistsService', function($scope, similarArtistsService) {
$scope.artists = [];
similarArtistsService.getArtists().success(function(response) {
console.log(response);
});
}]);
app.factory('similarArtistsService', ['$http', function($http) {
var similarArtists = {};
similarArtists.getArtists = function() {
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=artist.getSimilar&api_key=MYLASTFMAPIKEY&format=json&limit=5'
});
}
return similarArtists;
}]);
Without that, Angular uses parameter names to resolve dependencies. Many minifiers mangle those names.
Include your services before your controllers so the service is known at time of injection
Can you try switching to app.service('similarArtistsService', function($http) {}); since this will return the function instance as opposed to factory which will return the value.
When you declare your dependencies in AngularJS, don't close off the array until after the function. See square brackets of array:
controllers.js
app.controller('similarArtistsController', ['$scope', 'similarArtistsService', function($scope, similarArtistsService) {
// code in here
}]);
services.js
app.factory('similarArtistsService', ['$http', function($http) {
// code in here
}]);

Resources