我想要做的是使用服务将数据从控制器设置为另一个。
在我的代码中,服务成功更新数据,但数据未在第二个控制器中更新
HTML:
<div ng-app="App">
<div ng-controller="Cotroller1">
<p>{{test}}</p> <!-- still value 20, after button click -->
</div>
<div ng-controller="Cotroller2">
<button ng-click="changeValue(30)">test</button>
</div>
</div>
JS:
app.service('Service', function(){
var value = 20;
return {
getValue: function(){
return value;
},
setValue: function(newValue){
value = newValue;
}
};
});
app.controller('Cotroller1', function($scope, Service){
$scope.test = Service.getValue();
});
app.controller('Cotroller2', function($scope, Service){
$scope.changeValue = function(newValue){
Service.setValue(newValue);
alert(Service.getValue()); //proves the data was updated
};
});
对于我想要做的事情,这是一个很好的做法吗? 我错过了什么?
答案 0 :(得分:2)
只要我关心,使用事件是可行的方法。如果有人认为相反,我想知道原因:
var app = angular.module('App', []);
app.service('Service', function($rootScope){
var value = 20;
return {
getValue: function(){
return value;
},
setValue: function(newValue){
$rootScope.$broadcast("changeValue", newValue);
}
};
});
app.controller('Cotroller1', function($scope, Service){
//$scope.test = Service.getValue();
$scope.$on("changeValue",function(event, args){
$scope.test = args;
});
});
app.controller('Cotroller2', function($scope, Service){
$scope.changeValue = function(){
Service.setValue("12341234");
};
});
答案 1 :(得分:1)
您必须明确地观看该服务:
app.controller('Cotroller1', function($scope, Service){
$scope.$watch(function() {
return Service.getValue()
}, function(newVal) {
$scope.test = newVal;
});
});
服务中的更改不会传播到控制器,除非您将该服务中的更改绑定到控制器的摘要周期。 $watch
就是这么做的。