Reputation: 10422
I am trying to call a ajax from factory but it doesn't return me anything. My code given bellow
var msfaWebPortal = angular.module('MsfaWebPortal', [])
.factory('personFactory', function () {
var factory = {};
var people = [];
$.ajax({
url: '@Url.Action("GetPerson","Home")',
success: function (data) {
people = data;
}
});
factory.getPerson = function () {
return people;
};
return factory;
})
.controller('PersonCtrl', function ($scope, personFactory) {
$scope.friends = personFactory.getPerson();
$scope.predicate = '-age';
});
Am I missing something? Or How can I do it? Help me Please.
Upvotes: 3
Views: 8053
Reputation: 19569
You should use Angulars' $http for making these calls.
Ie.
var app = angular.module('myApp', []).config(/* config stuff */ );
app.PersonFactory = angular.factory('PersonResource', function($http) {
/* your code here */
/* when you want to make Ajax calls, use $http */
$http.get('/some/url/to/persons')
.success(function (response) {...})
.error(function(err){...});
/* keep going */
});
Additionally, if your Persons resource is RESTful, you can just use $resource, ie.
var app = angular.module('myApp', []).... /* setup app */
app.personsFactory = angular.factory('personsFactory', function($resource) {
var persons = $resource('/api/persons/:id', {id: '@id'});
return persons;
});
That way angular will know that on your /api/persons url it can GET persons, it can POST an new person, it can PUT an update for a person and DELETE a person.
Upvotes: 2