我在 AngularJS 中有两个具有相同 ng-controller 的 div,如何让它们共享信息? [英] I have two divs with the same ng-controller in AngularJS, how can I make them share information?
问题描述
我的 html 代码中有两个不同的 div 标签,它们引用了 AngularJS 中的同一个控制器.我怀疑的是,由于这些 div 不是嵌套的,因此它们每个都有自己的控制器实例,因此两者的数据不同.
<ul><li ng-repeat="alert in alerts"><div class="span4">{{alert.msg}}</div><div ng-controller="AlertCtrl"><form ng-submit="addAlert()"><button type="submit" class="btn">添加提醒</button></表单>
我知道这可以通过在第一个 div 中包含按钮来轻松解决,但我觉得这是一个非常干净和简单的示例,可以传达我想要实现的目标.如果我们按下按钮并将另一个对象添加到我们的警报数组中,则更改将不会反映在第一个 div 中.
function AlertCtrl($scope) {$scope.alerts = [{类型:'错误',msg: '哦,啪!更改一些内容,然后再次尝试提交.}, {类型:'成功',msg: '干得好!您已成功阅读此重要警报消息.}];$scope.addAlert = function() {$scope.alerts.push({类型:'成功',msg: "另一个警报!"});};}
这是一个很常见的问题.似乎最好的方法是创造服务/价值并在两者之间分享.
mod.service('yourService', function() {this.sharedInfo='默认值';});函数 AlertCtrl($scope, yourService) {$scope.changeSomething = function() {yourService.sharedInfo = '来自一个控制器的另一个值';}$scope.getValue = function() {返回 yourService.sharedInfo;}}
{{getValue()}}<div ng-controller="AlertCtrl">{{getValue()}}</div>
I have two different div tags in my html code referencing the same controller in AngularJS. What I suspect is that since these divs aren't nested they each have their own instance of the controller, thus the data is different in both.
<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>
I know this could easily be fixed by including the button in the first div but I feel this is a really clean and simple example to convey what I am trying to achieve. If we were to push the button and add another object to our alerts array the change will not be reflected in the first 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!"
});
};
}
This is a very common question. Seems that the best way is to create a service/value and share between then.
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>
这篇关于我在 AngularJS 中有两个具有相同 ng-controller 的 div,如何让它们共享信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!