I have two divs with the same ng-controller in AngularJS, how can I make them share information?

后端 未结 2 1254
执笔经年
执笔经年 2020-12-28 08:54

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 i

相关标签:
2条回答
  • 2020-12-28 09:31

    If I understand the question correctly, you want to sync two html areas with the same controller, keeping data synced.

    since these divs aren't nested they each have their own instance of the controller, thus the data is different in both

    This isn't true, if you declare the controllers with the same alias (I'm using more recente angular version):

    <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>
    

    However, if you WANT them to be different and comunicate each other, you will have to declare different aliases:

    <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>
    

    Then you can use services or broadcasts to comunicate between them (the second should be avoided, tough).

    0 讨论(0)
  • 2020-12-28 09:39

    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>
    
    0 讨论(0)
提交回复
热议问题