服务属性未绑定到范围

时间:2014-11-24 19:56:04

标签: angularjs angularjs-service

我有以下服务:

angular.module('myApp').factory('MyService', ['$http', function($http) {

    var resources = [];

    return {
        resources: resources,
        searchForResources: function(data) { return $http.post('/api/search'); },
    }

}]);

在我的控制器中,我有:

$scope.resources = MyService.resources;
MyService.searchForResources().then(function(response) {
    MyService.resources = response.data.resources;
});

我的API调用实际上正在返回正确的数据,并且正在设置MyService.reources,只是$ scope.resources没有使用MyService.resources的新值更新(我必须手动执行此操作) )。

$scope.resources = MyService.resources是否应设置$ watch,以便每当MyService.resources更改时,它还会更新$ scope.resources的值?我怎么能这样做呢?

修改 目前,使用$scope.$watch(function() { return SearchService.resources; }, function(newValue) { $scope.resources = newValue; });就足够了。

2 个答案:

答案 0 :(得分:0)

如果我可以提出一些改进(但它没有做同样的事情):

angular.module('myApp').factory('MyService', ['$http', function($http) {
    var resources = [];
    return {
        searchForResources: function(callback) { 
            if (resources) {
                callback(resources)
            } else { 
                $http.post('/api/search').success(function(data){
                  resources = data
                  callback(resources)
                }
            }
        }
    }
}]);

并在控制器中:

MyService.searchForResources(function(resources){
   $scope.resources = resources
}

我希望它可以帮助你...

答案 1 :(得分:0)

我会解决您服务中$http.post的响应,以避免这种情况。尝试这样的事情:

angular.module('myApp', [ 'myControllers', 'myServices' ]);

angular.module('myServices', [])
.factory('MyService', function($http) {
  
  var MyService = {};
  
  MyService.resources = [];

  MyService.searchForResources = function () {
    return $http.post('/api/search')
    .success(function (response) {
      MyService.resources = response;
    })
    .error(function () {
      MyService.resources = ['error'];
    });
  };
  
  return MyService;

});

angular.module('myControllers', [])
.controller('MyController', function(MyService, $scope) {

  $scope.resources = MyService.resources;
  
  // Don't need both success and error handlers here... can just use then handler instead
  // Doing this for demo purposes.
  MyService
    .searchForResources()
    .success(function () {
      $scope.resources = MyService.resources;
    })
    .error(function() {
      $scope.resources = MyService.resources;
    });
});
<html>
  <head>
    <title>My App!</title>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body ng-app="myApp" ng-controller="MyController">
    <div>
      {{ resources }}
    </div>
  </body>
</html>