【问题标题】:AngularJS : Custom directive scope not being initialized properly when used with ng-repeatAngularJS:与 ng-repeat 一起使用时,自定义指令范围未正确初始化
【发布时间】:2013-12-09 08:04:51
【问题描述】:

我在将对象信息传递给具有隔离范围的自定义指令时遇到问题。我把我的问题归结为这个简单的 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) {

    }
  }
});

谢谢。

【问题讨论】:

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


    【解决方案1】:

    问题:

    • 从指令函数中删除$scope
    • 从 HTML 中删除 ng-repeat 之后的逗号

    为元素提供新属性,例如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

    【讨论】:

    • 你知道为什么必须创建一个新属性并将其分配给它吗?如果我可以将它直接传递给指令的名称会更整洁。
    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2014-10-23
    • 2014-12-26
    • 2015-07-01
    相关资源
    最近更新 更多