How to make a variable change in one directive to be reflected in another directive

How to change the value of bara directive2so that it is reflected in thedirective1

If I do scope:false, this happens.
Is there any other way for this to happen. (because in the code that I write, I can not do scope:false).
My main requirement is to make one directive to communicate with another.
Here you can try the plunkr version of the code below

HTML snippet

<body ng-controller="MainCtrl">
  this is directive1: <div directive1></div>.<br/>
  this is directive2: <div directive2></div>.
</body>

js fragment

var app = angular.module('myApp', []);

app.directive('directive1', function() {
    return {
        restrict: 'A',

        replace: true,
        template: '<span>{{bar}}</span>'
    }

    });

app.directive('directive2', function() {
  return {
      restrict: 'A',
      scope:{


      },
       replace: true,
       link:function(s,e,a){
         s.bar = "Changed value";
       },
       template: '<b>{{bar}}</b>'
  }

});

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.bar ="original value";
});
+4
source share
3 answers

bar , , bar. , bar .

<body ng-controller="MainCtrl">
  this is directive1: <div directive1></div>.
  <br />
  this is directive2: <div directive2 bar="bar"></div>.
</body>

app.directive('directive2', function() {
  return {
      restrict: 'A',
      scope:{
        'bar': '=' //<-- Change here
      },
       replace: true,
       link:function(s,e,a){
         s.bar = "Changed value";
       },
       template: '<b>{{bar}}</b>'
  }

});

Plunkr

+3

, '=' , , .

<body ng-controller="MainCtrl">
  this is directive1: <div directive1 bar="bar"></div>.
  <br />
  this is directive2: <div directive2 bar="bar"></div>.
</body>

var app = angular.module('myApp', []);
app.directive('directive1', function() {
return {
    restrict: 'A',
    scope:{bar:'='},
    replace: true,
    template: '<span>{{bar}}</span>'
}

});

app.directive('directive2', function() {
  return {
    restrict: 'A',
    scope:{bar:'='},
    replace: true,
    link:function(s,e,a){
      s.bar = "Changed value";
    },
   template: '<b>{{bar}}</b>'
}

});

app.controller('MainCtrl', function($scope) {
 $scope.name = 'World';
 $scope.bar ="original value";
});
+2

$-, - angularjs .

:

$rootScope.$on('myEvent', function (event, data) {
  $scope.bar = data.bar;
});

, :

$scope.$emit('myEvent', {bar: bar});

, .

0

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


All Articles