javascript - AngularJS : Getting data from Factory and update Controller scope and view

标签 javascript angularjs angularjs-service angularjs-controller angular-promise

大家好,我真的需要关于我遇到的这个工厂和 Controller 问题的帮助和建议。

  1. 我有一个从服务器获取数据的工厂

    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;
    }]);
    
  2. 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/

相关文章:

Javascript + queryselector 支持所有带有类名的特殊字符

javascript - Joyride 基础自定义覆盖

angularjs - $httpBackend.flush() 方法抛出错误 : [$rootScope:infdig] 10 $digest() iterations reached. 中止

javascript - AngularJS "value"服务可以保存正则表达式吗?

angularjs - 初始化非注入(inject) angular.service

javascript - Vanilla JS : How to target an input element by the input-field's name ("name" in DOM tree)?

javascript - 使用 jquery getjson 检索 JSON 提要?

javascript - AngularJS 模板重新加载并且页面消失

javascript - 为什么 'this' 在新的 Angular 1.5 组件中丢失上下文?

javascript - 创建通用 Controller 函数