AngularJS:与ng-repeat一起使用时,自定义指令范围未正确初始化

时间:2013-12-09 08:04:51

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

我将对象信息传递给我的自定义指令时出现问题,该指令具有隔离范围。我把问题归结为这个简单的plnkr,以展示我正在打击的墙:

http://plnkr.co/edit/oqRa5pU9kqvOLrMWQx1u

我只是错误地使用ng-repeat和指令吗?同样,我的目标是将对象信息从ng-repeat循环传递到我的指令中,该指令将具有自己的范围。

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) {

    }
  }
});

谢谢。

1 个答案:

答案 0 :(得分:1)

的问题:

  • 从指令功能
  • 中删除$scope
  • ng-repeat
  • 之后从HTML中删除逗号

为元素提供新属性,例如value,但my-directive="i"也可以。

<强> 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);
    }
  }
});

演示 Plunker