繁体   English   中英

我在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不是嵌套的,所以每个div都有自己的控制器实例,因此两者的数据都不同。

<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中包含按钮轻松修复,但我觉得这是一个非常简洁的例子来传达我想要实现的目标。 如果我们按下按钮并将另一个对象添加到警报数组中,则更改将不会反映在第一个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!"
    });
};
}

这是一个非常常见的问题。 似乎最好的方法是创建一个服务/值并在那之间共享。

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>

如果我正确理解了这个问题,你想用同一个控制器同步两个html区域,保持数据同步。

由于这些div不是嵌套的,因此每个div都有自己的控制器实例,因此两者的数据都不同

如果您使用相同的别名声明控制器(我使用更多的临时角度版本),则情况并非如此:

<div ng-controller="AlertCtrl as instance">
  {{instance.someVar}}
</div>
<div ng-controller="AlertCtrl as instance">
  {{instance.someVar}} (this will be the same as above)
</div>

但是,如果您希望它们彼此不同并相互通信,则必须声明不同的别名:

<div ng-controller="AlertCtrl as instance1">
  {{instance1.someVar}}
</div>
<div ng-controller="AlertCtrl as instance2">
  {{instance2.someVar}} (this will not necessarily be the same as above)
</div>

然后你可以使用服务或广播在它们之间进行交流(第二个应该避免,很难)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM