【发布时间】:2017-05-02 12:03:38
【问题描述】:
我正在尝试使用服务将信息从一个控制器传递到另一个控制器。
它工作正常,但在下面的 sn-p/Fiddle 中,我必须:
- 在输入中输入值
- 点击
FirstController中的“设置值”按钮 - 点击
SecondController中的“获取价值”按钮 - 现在显示值
我希望更新后的值自动显示在SecondController中。
angular.module('app', []);
angular.module('app').factory('StoreService', function () {
var storedObject;
return {
set: function (o) {
this.storedObject = o;
},
get: function () {
return this.storedObject;
}
};
});
angular.module('app').controller('FirstController', function ($scope, StoreService) {
$scope.setValue = function (value) {
StoreService.set(value);
};
});
angular.module('app').controller('SecondController', function ($scope, StoreService) {
$scope.getValue = function () {
$scope.value = StoreService.get();
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="FirstController">
<fieldset>
<legend>FirstController:</legend>
<input type="text" ng-model="value" />
<button ng-click="setValue(value)">Set value</button>
</fieldset>
</div>
<div ng-controller="SecondController">
<fieldset>
<legend>SecondController:</legend>
<button ng-click="getValue()">Get value</button>
Value: {{value}}
</fieldset>
</div>
</div>
Fiddle
【问题讨论】:
-
如果它们在同一个页面上并处理相同的数据,为什么要有两个独立的控制器?
标签: angularjs angular-services