本文介绍了AngularJS:与 ng-repeat 一起使用时,自定义指令范围未正确初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将对象信息传递给具有隔离作用域的自定义指令时遇到问题.我已经将我的问题归结为这个简单的 plnkr 来演示我正在击中的墙:

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

我是否只是错误地使用了 ng-repeat 和指令?同样,我的目标是将对象信息从 ng-repeat 循环传递到我的指令中,该指令将有自己的作用域.

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

    }
  }
});

谢谢.

推荐答案

问题:

  • 从指令函数中删除 $scope
  • 从 HTML 中删除 ng-repeat
  • 之后的逗号
  • remove $scope from directive function
  • remove comma from HTML after ng-repeat

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

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

演示

这篇关于AngularJS:与 ng-repeat 一起使用时,自定义指令范围未正确初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:31