我的 html 代码中有两个不同的 div 标签引用了 AngularJS 中的同一个 Controller 。我怀疑的是,由于这些 div 没有嵌套,它们每个都有自己的 Controller 实例,因此两者的数据不同。
<div ng-controller="AlertCtrl">
<ul>
<li ng-repeat="alert in alerts">
<div class="span4">{{alert.msg}}</div>
</li>
</ul>
</div>
<div ng-controller="AlertCtrl">
<form ng-submit="addAlert()">
<button type="submit" class="btn">Add Alert</button>
</form>
</div>
我知道这可以很容易地通过在第一个 div 中包含按钮来解决,但我觉得这是一个非常干净和简单的示例来传达我想要实现的目标。如果我们按下按钮并将另一个对象添加到我们的警报数组中,则更改将不会反射(reflect)在第一个 div 中。
function AlertCtrl($scope) {
$scope.alerts = [{
type: 'error',
msg: 'Oh snap! Change a few things up and try submitting again.'
}, {
type: 'success',
msg: 'Well done! You successfully read this important alert message.'
}];
$scope.addAlert = function() {
$scope.alerts.push({
type: 'sucess',
msg: "Another alert!"
});
};
}
最佳答案
这是一个很常见的问题。似乎最好的方法是创建服务/值(value)并在两者之间共享。
mod.service('yourService', function() {
this.sharedInfo= 'default value';
});
function AlertCtrl($scope, yourService) {
$scope.changeSomething = function() {
yourService.sharedInfo = 'another value from one of the controllers';
}
$scope.getValue = function() {
return yourService.sharedInfo;
}
}
<div ng-controller="AlertCtrl">{{getValue()}}</div>
<div ng-controller="AlertCtrl">{{getValue()}}</div>
关于javascript - 我在 AngularJS 中有两个具有相同 ng-controller 的 div,如何让它们共享信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15170464/