大家好,我真的需要关于我遇到的这个工厂和 Controller 问题的帮助和建议。
我有一个从服务器获取数据的工厂
sp.factory('homeFeed',['$window','$http','auth',function($window,$http,auth){ var url = auth.url; var version = auth.version; var HomeFeed = {}; HomeFeed.getFeeds = function(user){ //setting variable for get request on home feed var req = { method: 'GET', url: url + version + '/Feed', headers: { 'Content-Type': 'application/json; charset=utf-8', 'Authorization': 'Bearer ' + token }, } return $http(req).success(function(res){ return res; }); }; return HomeFeed; }]);
Controller --
sp.controller('HomeCtrl',['$scope','homeFeed','$window',function($scope,homeFeed,$window){ //getting all the home feed data $scope.feeds = homeFeed.getFeeds(JSON.parse($window.localStorage['SP-User'])) }]);
但是,在服务器响应后,我的 View 没有更新,$scope.feeds也没有更新。非常感谢您的帮助
最佳答案
当您正在进行异步 $http
调用时,该数据在该时刻将不可用。 ajax调用成功后即可使用。您需要使用 .then
函数来创建一个 Promise 链,并在 .success
函数返回数据时执行函数。
Controller
sp.controller('HomeCtrl',['$scope','homeFeed','$window',
function($scope,homeFeed,$window){
//getting all the home feed data
homeFeed.getFeeds(JSON.parse($window.localStorage['SP-User']))
.then(function(data){
$scope.feeds = data
});
}
]);
关于javascript - AngularJS : Getting data from Factory and update Controller scope and view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31796242/