AngularJs将HTML中每个ng-repeat的实例传递给指令

问题描述 投票:6回答:1

我认为这应该很简单,但是我缺少了一些东西。如何将下面flowObj中的ng-repeat传递给指令?我想将其传递给我的指令,然后在单击时使用该FlowObj,然后应用一些逻辑。我尝试在指令中使用注释的代码

scope: { 
    test:"@" 
}

但是它似乎弄糟了我的CSS。

HTML:

<html>
   <head>
      <title></title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   </head>
   <body>
      <div id="center_outer">
         <div id="center_inner" ng-controller="CtrlPageFlow">
            <div flowclick class="cflow" ng-repeat="flowObj in flows">
               {{flowObj.name}}
            </div>
         </div>
      </div>
   </body>
</html>

这是我的指令

angular.module('directives', ['opsimut']).directive('flowclick', function() {
    return {   
        /* 
        scope: {
            test:"@"   // set the attribute name on the directive's scope
        },
        */
        link: function(scope, elem, attr) {
            elem.bind('click', function(scope) {
                debugger;
                alert(scope.flowObj);
                //scope.name += '!';
                //scope.$apply();
            });
        }
    };
});

基于答案的解决方案:

angular.module('directives', ['opsimut']).
directive('flowclick', function() {
  return {
    link: function(e, elem, attr) {
      // scope is the directive's scope,
      // elem is a jquery lite (or jquery full) object for the directive root element.
      // attr is a dictionary of attributes on the directive element.
      elem.bind('click', function(e1) {
        debugger;
        alert(e.flowObj);
      }, e);
    }
  };
});
javascript css angularjs angularjs-directive angularjs-ng-repeat
1个回答
7
投票

SOLUTION:从指令中删除整个scope属性,所有内容都应按预期工作。

ALSO:您需要从此行重命名scope参数:

elem.bind('click', function(scope) {

到类似的东西:

elem.bind('click', function(e) {

因为您正在使用相同的名称覆盖事件处理程序中对scope的访问权限。

EXPLANATION:

ng-repeat指令使每个克隆具有自己的新作用域。由于默认情况下,元素上的指令共享作用域,因此与ng-repeat一起放置的任何其他指令都共享其作用域,并可以访问当前迭代的$scope变量。换句话说,您的自定义指令已与ng-repeat共享范围,并且默认情况下可以访问flowObj

在自定义指令上指定scope属性时,该指令不起作用的原因是,这导致该指令具有自己的隔离范围,该范围与ng-repeat不共享,因此您无法访问以下变量:克隆的范围。

© www.soinside.com 2019 - 2024. All rights reserved.