想象一下,我的导航栏位于导航栏控制器上,我正在另一个控制器中进行值操作,我如何更新导航栏的值?
这是我为表达问题而创建的一个小例子
<div ng-app="app">
<div ng-controller="ctrl">
{{number}}
<br><button ng-click="increment()">Increment</button>
</div>
<br>
<br>
<div ng-controller="ctrl2">
{{number || 0}}
</div>
</div>
angular.module("app", [])
.controller("ctrl", ["$scope", function($scope){
$scope.number = 1;
$scope.increment = function(){
$scope.number++;
}
}])
.controller("ctrl2", ["$scope", function($scope){
}]);
我想更新ctrl2控制器的{{number}}。
答案 0 :(得分:0)
因此,您希望在控制器中共享成员。实际上有不同的方法来实现这一点,但我建议创建一个父控制器,如下所示:
angular.module("app", [])
.controller("parent", ["$scope", function($scope){
$scope.number = 0;
}]
.controller("ctrl", ["$scope", function($scope){
$scope.number = 1;
$scope.increment = function(){
$scope.number++;
}
}])
.controller("ctrl2", ["$scope", function($scope){
$scope.number= 1;
}]);
并在html中:
<div ng-app="app" ng-controller="parent">
<div ng-controller="ctrl">
{{number}}
<br><button ng-click="increment()">Increment</button>
</div>
<br>
<br>
<div ng-controller="ctrl2">
{{number || 0}}
</div>
</div>
我相信这是一种干净利落的方式。
答案 1 :(得分:0)
之间共享数据的干净方式始终使用Angular Service。这是我根据你的例子改变的代码。基本上
angular.module("app", [])
.factory("sharedModelService", function() {
var model = this;
var number = 0;
model.initNumber = function(value) {
return number = value;
}
model.getNumber = function() {
return number;
}
model.increment = function() {
return ++number;
}
return model;
})
.controller("ctrl", ["$scope", "sharedModelService", function($scope, sharedModelService) {
sharedModelService.initNumber(1);
$scope.getNumber = sharedModelService.getNumber;
$scope.increment = function() {
sharedModelService.increment();
}
}])
.controller("ctrl2", ["$scope", "sharedModelService", function($scope, sharedModelService) {
$scope.getNumber = sharedModelService.getNumber;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="ctrl">
{{getNumber()}}
<br>
<button ng-click="increment()">Increment</button>
</div>
<br>
<br>
<div ng-controller="ctrl2">
{{getNumber() || 0}}
</div>
</div>