2014-11-24 70 views
0

我有以下服務:服務屬性不綁定到範圍

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; });就足夠了。

回答

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 
} 

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

+0

謝謝,但我真的想用我的控制器內的'。那麼()'邏輯。我發佈的代碼被編輯以使問題更容易理解,實際上服務中有更多的變量以及我需要做的一些其他綁定 - 您的代碼對於我的簡單示例可能會更好,但它會使事情更加複雜很難在我的真實代碼中工作。 我知道我可以使用'$ watch'和'$ broadcast',但是我希望能夠按照我想象中的方式使用它。 – chipit24 2014-11-24 20:45:55

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>