问题描述
我在我的html code两个不同的div标签引用在AngularJS同一个控制器。我怀疑的是,由于这些div都是没有嵌套他们每个人都有自己的控制器的实例,因此数据是在两个不同的。
< DIV NG控制器=AlertCtrl>
< UL>
<李NG重复=警戒警报中>
< DIV CLASS =span4> {{alert.msg}}< / DIV>
< /李>
< / UL>
< / DIV>
< DIV NG控制器=AlertCtrl>
<形式NG提交=addAlert()>
<按钮式=提交级=BTN>添加警报< /按钮>
< /表及GT;
< / DIV>
我知道这很容易通过在第一个div按键是固定的,但我觉得这是一个非常干净和简单的例子来表达什么,我想要的目的。如果我们按下按钮,添加另一个目的是我们的警示阵列的变化会不会反映在第一个div。
函数AlertCtrl($范围){$ scope.alerts = [{
类型:'错误',
味精:哦,糟糕!改变一些事情,并尝试重新提交。
},{
类型:'成功',
味精:干得好!你成功读取这个重要的警报消息。
}];$ scope.addAlert =功能(){
$ scope.alerts.push({
类型:'sucess',
味精:另一个警报!
});
};
}
这是一个非常普遍的问题。看来,最好的办法是创建那么之间的服务/价值和份额。
mod.service('yourService',函数(){
this.sharedInfo =默认值;
});
功能AlertCtrl($范围,yourService){
$ scope.changeSomething =功能(){
yourService.sharedInfo ='从控制器之一另一个值';
} $ scope.getValue =功能(){
返回yourService.sharedInfo;
}
}
< DIV NG控制器=AlertCtrl> {{的getValue()}}< / DIV>
< DIV NG控制器=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>
这篇关于我有两个div与AngularJS相同NG控制器,如何才能让他们共享信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!