Communication between two modules in AngularJs

后端 未结 3 761
盖世英雄少女心
盖世英雄少女心 2021-02-07 14:08

This is rather simple to imagine, but I haven\'t found any resources mentioning what is correct approach to this issue.

I\'d like to broadcast event in one angular

3条回答
  •  情书的邮戳
    2021-02-07 14:44

    I just want to know how to do it properly.

    "Properly" is pretty subjective. "Properly" is whatever works, is easy to understand and is maintainable.

    That said, why not just use $window to pass the values between the two separate running angular apps?

    function persistFoo($scope, $window) {
       //watch window.foo
       $scope.$watch(function (){
          return $window.foo;
       }, function(v) {
          if($scope.foo !== v) {
             $scope.foo = v;
          }
       });
    
       //watch scope.foo
       $scope.$watch('foo', function(v) {
          if($window.foo !== v) {
             $window.foo = v;
          }
       });
    }
    
    //Module 1
    app1.controller("MyCtrl1", function($scope, $window) {
      persistFoo($scope, $window);
    });
    
    //Module 2
    app2.controller("MyCtrl2", function($scope, $window) {
      persistFoo($scope, $window);
    });
    

    localStorage will work too, if you need to persist the data for subsequent visits.

提交回复
热议问题