AngularJs $scope doesn't update after a GET request on a factory
angularjs, angularjs-scope, httprequest, javascript
Solution
Using a watch for that is kinda ugly.
try this:
datModule.factory('datfactory', function ($http, $q){
this.getlist = function(){
return $http.get('http://localhost:61686/getdatlist?format=json',{'Access-Control-Allow-Origin': 'localhost:*'})
.then(function(response) {
console.log(response); //I get the correct items, all seems ok here
return response.data.itemsToReturn;
});
}
return this;
});
datModule.controller('datlist', function ($scope, datfactory){
datfactory.getlist()
.then(function(arrItems){
$scope.items = arrItems;
});
});
This is how you use promises for async matter.
UPDATE (15.01.2015): Now even sleeker!
Problem
I have been trying AngularJS for a experimental project and I came along with this problem. In my html I want to display a list of items Index.html ``` <h1>Some list</h1> <div ng-controller="datlist"> <div ng-repeat="item in items"> <div>Item description: {{item.description}}</div> <div>Item name: {{item.name}}</div> </div> </div> ``` At first I was using a simple controller to get the information and update the view just using this: controllers.js (original) ``` function datlist($scope,$http){ $http({method: 'GET', url: 'http://localhost:61686/getdatlist?format=json', headers: {'Access-Control-Allow-Origin': 'localhost:*'}}). success(function(data, status, headers, config) { $scope.items=data.itemsToReturn; console.log(data); }). error(function(data, status, headers, config) { console.log("fail"); }); } ``` This was working pretty well and I could get the list of items. Whilst, by changing my structure to use a factory to make the same request and bind it to $scope.items it doesn't work. I tried a lot of variations of $watch but I couldn't get it to update $scope.items. I found something about $apply but I really can't understand how to use it. controllers.js (new one) ``` var datModule = angular.module('datModule',[]); datModule.controller('datlist', function ($scope, datfactory){ $scope.items = datfactory.getlist(); $scope.$watch($scope.items, $scope.items = datfactory.getlist()); }); datModule.factory('datfactory', function ($http){ var factory = {}; factory.getlist = function(){ $http({method: 'GET', url: 'http://localhost:61686/getdatlist?format=json', headers: {'Access-Control-Allow-Origin': 'localhost:*'}}). success(function(data, status, headers, config) { console.log(data.itemsToReturn); //I get the correct items, all seems ok here return data.itemsToReturn; }). error(function(data, status, headers, config) { console.log("fail"); }); } return factory; }); ``` Any ideas about this will be great. PS: I found a lot of posts talking about this issue but none of them helped me to get a full solution. Thanks