AngularJS:自定义指令范围与NG-重复使用时,没有正确初始化 [英] AngularJS : Custom directive scope not being initialized properly when used with ng-repeat

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

问题描述

我有传递对象信息到我的自定义指令,它有一个分离范围的问题。我已经煮了我的问题,下到简单的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-重复和指令不正确?同样,我的目标是通过从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) {

    }
  }
});

感谢您。

推荐答案

问题:


  • 删除 $范围从指导作用

  • 后删除HTML逗号 NG-重复

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

演示<大骨节病> Plunker

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆