AngularJS: how to reflect a variable change in one directive to another directive when using ng-repeat

In the first case : I applied a directive directive2that will change the value bar, which will also be reflected in directive1.
Here you can find plunkr (1st case) In the second case : I applied the directive , c , used with this directive, which changes the value , and this should be reflected in . Here you can find plunkr for using (second case)

directive2ng-repeatbardirective1
directive2ng-repeat

I expect that it will work : I want barto directive1change in accordance with changes in thedirective2

My question is: 1st case works the way I want. In the second case, the value of my barin directive1does not change in accordance with the changes made to directive2.
My guess is that using ng-repeatcreates several areas and therefore does not work the way I want.

How can i solve this?

HTML snippet (second case)

<body ng-controller="MainCtrl">
    this is directive1: <directive1></directive1>
    <br />
    <div ng-repeat="item in [1,2]"> 
        this is directive2 for ng-repeat {{item}}
        <directive2 bar="bar"></directive2>
    </div>
</body>

JS fragment (second case)

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

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

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

 });

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

});

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

! - , ng-repeat.

bar, set bar . ng-repeat - ng-repeat , , .

, , . plunkr http://plnkr.co/edit/JCQsIXzRv9FUNfJwhOAB?p=preview

bar

$scope.data={};
$scope.data.bar ="original value";

<directive2 bar="data.bar"></directive2>

+4

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


All Articles