Updating $ scope between two controllers

It is very difficult to explain, but I will try, please remember this.

I am creating an angularJS application and I am having problems updating the user interface ($ scope).

See diagram here enter image description here

You can see that there are 2 controllers and 3 different $ scope at the same time. For example, if I edit the "Title" in $ scope3, the "Title" should also change in $ scope2.

What is the best way to control changes and pass values ​​between controllers and pass them to $ scope.value or force use of a new call to $ resource.

I am completely lost here.

+4
source share
1 answer

. , ..

, . , - , , .

1 1

<div ng-controller="Ctrl1">
  <input type="text" ng-model="val">{{ val }}
</div>

1 1

app.controller('Ctrl1', ['$scope', 'ValMediator', function($scope, ValMediator) {
 $scope.val = '';

 $scope.$watch(
   function(){
     return ValMediator.getVal();
   },
   function(newVal){
     $scope.val = newVal;
   }
 );

 $scope.$watch('val',
   function(newVal){
     ValMediator.setVal(newVal);
   }
 );

}]);

2 2

<div ng-controller="Ctrl2">
  <input type="text" ng-model="val">{{ val }}
</div>  

2 2

app.controller('Ctrl2', ['$scope', 'ValMediator',function($scope, ValMediator) {
  $scope.val = '';

  $scope.$watch(
    function(){
      return ValMediator.getVal();
    },
    function(newVal){
      $scope.val = newVal;
    }
  );

  $scope.$watch('val',
    function(newVal){
      ValMediator.setVal(newVal);
  }
 );

 }]);

app.factory('ValMediator', function() {
  var val = '';
  return {
    setVal: function(newVal){
      val = newVal;
    },
    getVal: function(){
      return val;
    }
  };
});

, jsBin ValMediator - , val getter . . $scope.$watch , $scope. val .

=====================

- $rootScope. , , rootScope , . / .

jsBin

$rootScope, . , $scope $rootScope :

1 1

app.controller('Ctrl1', ['$scope', '$rootScope', function($scope, $rootScope) {
  $scope.val = '';

  $scope.$on('Val/update', function(e, arg){
    console.log('val update 1', arg);
    $scope.val = arg;
  });

  $scope.$watch('val',
    function(newVal, oldVal){
      if (newVal === oldVal) return;
      $rootScope.$broadcast('Val/update', newVal);
  }
);

}]);

2 2

app.controller('Ctrl2', ['$scope', '$rootScope',function($scope, $rootScope) {
  $scope.val = '';

  $scope.$on('Val/update', function(e, arg) {
    console.log('val update 2', arg);
    $scope.val = arg;
  });

  $scope.$watch('val',
    function(newVal, oldVal) {
      if (newVal === oldVal) return;
      $rootScope.$broadcast('Val/update', newVal);
    }
  );

}]);

- .

+4

Source: https://habr.com/ru/post/1526940/


All Articles