我有两个控制器和一个共享服务。第一个控制器呈现一些文本。其他控制器有一个按钮,必须更改第一个控制器范围并重新呈现文本(具有新值)
HTML
<div ng-controller="Controller1">
Value is: {{object}}
</div>
<div ng-controller="Controller2">
<button ng-click="changeValue()">Click to change Value</button>
</div>
JS
function Controller1($scope, mainServices) {
$scope.object = mainServices.getValue();
};
function Controller2($scope, mainServices) {
$scope.changeValue = function(){
mainServices.getValue('Hello');
console.log('button is pressed');
};
};
testApp.factory('mainServices', function(){
return {
getValue: function(update) {
var defaultValue = 'Hi';
if( typeof(update)==='undefined') { value = defaultValue; }
else { value = update; }
console.log('should be changed to', update);
return value;
}
}
});
在 Plunker http://plnkr.co/edit/IWBEvAfvLbzJ0UD2IqGB?p=preview
为什么这不起作用?如何告诉 Angular 留意变化?