Angular Service使用Factory,数据正确但未在UI上显示

时间:2016-05-13 10:31:09

标签: javascript angularjs

到目前为止,这是the complete source

angular
.module('app')
.factory('Friends', ['$http',function($http){
    return {
        get: function(){
            return $http.get('api/friends.json')
              .then(function(response){
                alert(JSON.stringify( response.data));
                return response.data;
              });
        }
    };
}])

控制器:

angular.module("app")
.controller('homeCtrl',['$scope','Friends',
    function($scope, Friends){
            $scope.title = "Welcome";
            $scope.items=["2016","2015", "2014"];
            $scope.friends = Friends.get();
            $scope.save = function(){
                $http.post('/api/friends', friends);
            }

          }])

$stateProvider
        .state('home',{
          url:'/',
          templateUrl:'templates/home.html',
          controller: 'homeCtrl',
          resolve : {
            friends:['Friends', function(Friends){
            return Friends.get();
          }]
          }
        })

我尝试提醒时的结果:

enter image description here

UI空白: enter image description here

*和我的导航条ddl无法正常工作?

enter image description here

2 个答案:

答案 0 :(得分:2)

Friends.get()返回一个promise。您必须使用then方法:

Friends.get().then(function(data) { $scope.friends = data; }); //instead of  $scope.friends = Friends.get();

答案 1 :(得分:1)

你应该使用$ q作为承诺:

angular
.module('app')
.factory('Friends', ['$http', '$q' ,function($http, $q){
    var self = {};
    self.get = function() {

      var deferred = $q.defer();
      $http.get('api/friends.json')
      .success(deferred.resolve)
      .error(deferred.reject)

      return deferred.promise;
    }

   return self
}])

消退:

 resolve : {
   friends:['Friends', function(Friends){
     return Friends.get();
   }]
 }