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

 ̄綄美尐妖づ 提交于 2019-12-10 11:02:31

问题


In first case: I implemented a directive directive2 that will change bar value which will also get reflected in directive1.
Here u can find the plunkr (1st case)

In second case:I implemented a directive directive2, with ng-repeat used along with this directive that changes bar value and this is supposed to get reflected in directive1.
Here u can find the plunkr for directive2 with ng-repeat(2nd case)

How i expect it to work: i want the bar in directive1 to change according to the change in directive2

My question: 1st case is working the way i want. In the 2nd case my bar value in directive1 is not changing according to changes made in directive2.
My assumption is that using ng-repeat is creating multiple scopes and hence not working the way i want.

How do i solve this?

HTML snippet(2nd 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 snippet(2nd 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";
});

回答1:


You have correctly guessed it! This is happening because of child scopes created by ng-repeat.

When you are creating a isolated scope with bar dependency the set operation on bar is setting the bar value on parent scope. In case of ng-repeat the parent scope is the ng-repeat scope and hence this behaviour.

Use a object instead of string to pass the string reference around and it will work. Check my plunkr http://plnkr.co/edit/JCQsIXzRv9FUNfJwhOAB?p=preview

Set bar variable as

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

User directive like

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



来源:https://stackoverflow.com/questions/29874648/angularjs-how-to-reflect-a-variable-change-in-one-directive-into-another-direc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!