AngularJS : Custom directive scope not being initialized properly when used with ng-repeat

懵懂的女人 提交于 2019-12-11 14:54:02

问题


I have a problem with passing object information to my custom directive, which has an isolate scope. I have boiled my problem down to this simple plnkr to demonstrate the wall I am hitting:

http://plnkr.co/edit/oqRa5pU9kqvOLrMWQx1u

Am I just using ng-repeat and directives incorrectly? Again, my goal is to pass the object information from the ng-repeat loop into my directive which will have its own scope.

HTML

<body ng-controller="MainCtrl">
    <ul>
      <li ng-repeat="i in items", my-directive="i">
        <span>{{$index}}</span>
        <p>{{item.name}}</p>
        <p>{{item.value}}</p>
      </li>
    </ul>
  </body>

JS

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

app.controller('MainCtrl', function($scope) {
  $scope.items = [
      {name: "Name #1", value: "Value #1"},
      {name: "Name #2", value: "Value #2"},
      {name: "Name #3", value: "Value #3"}
    ];
});

app.directive('myDirective', function($scope) {
  return {
    restrict: "A",
    scope: { item: "=myDirective" },
    link: function(scope, elem, attrs) {

    }
  }
});

Thank you.


回答1:


Issues:

  • remove $scope from directive function
  • remove comma from HTML after ng-repeat

Provide element with new attribute, for example value but my-directive="i" will work as well.

HTML

 <ul>
      <li ng-repeat="i in items" my-directive value="i">
        <span>{{$index}}</span>
        <p>{{item.name}}</p>
        <p>{{item.value}}</p>
      </li>
    </ul>

JS

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

app.controller('MainCtrl', function($scope) {
  $scope.items = [
      {name: "Name #1", value: "Value #1"},
      {name: "Name #2", value: "Value #2"},
      {name: "Name #3", value: "Value #3"}
    ];
});

app.directive('myDirective', function() {
  return {
    restrict: "A",
    scope: { item: "=value" },
    link: function(scope, elem, attrs) {
      console.log(scope.item);
    }
  }
});

Demo Plunker



来源:https://stackoverflow.com/questions/20465840/angularjs-custom-directive-scope-not-being-initialized-properly-when-used-with

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