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