由于某种原因,角度控制器不会更新视图

时间:2014-05-14 17:34:11

标签: angularjs

我的服务看起来像:

myApp.service('peerService', [
  '$http', function($http) {
    this.getPeers = function() {
      return $http({
        url: '/api/v1/peers',
        method: 'GET'
      });
    };
  }
]);

在我的控制器中,我有:

myApp.controller('PeerComparisonController', [
  '$scope', '$rootScope', 'peerService', function($scope, $rootScope, peerService) {
    $scope.init = function() {
      $rootScope.pageTitle = 'Peer Comparison';
      return $scope.peers = [];
    };
    $scope.getPeers = function() {
      return peerService.getPeers().then(function(response) {
        console.log(response);
        return $scope.peers = response.data;
      });
    };
    return $scope.init();
  }
]);

我的观点中有{{ peers }}。服务返回时,这不会更新。我试过了:

peerService.getPeers().then(function(response) {
  return $scope.$apply(function() {
    return $scope.peers = response.data;
  });
});

这也不起作用。那么任何想法?

1 个答案:

答案 0 :(得分:1)

你尝试这样的事情

myApp.service('peerService', [
  '$http', function($http) {
    this.getPeers = function() {
    return $http({method: 'GET', url:'/api/v1/peers'}).
         then(function(response) {
                  return response.data;
         });

    };
  }
]);

myApp.service('peerService', ['$http', function ($http) {
      this.getPeers = function () {
          var deferred = $q.defer();
          $http({ method: 'GET', url: '/api/v1/peers' }).
               then(function (response) {
                   deferred.resolve(response.data);
               });

          return deferred.promise;
      };
  }
]);