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

后端 未结 2 1260
执笔经年
执笔经年 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: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;
      }
    }
    
    {{getValue()}}
    {{getValue()}}

提交回复
热议问题