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

Mik*_*679 6 angularjs angularjs-directive angularjs-ng-repeat

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

scope: { 
    test:"@" 
}
Run Code Online (Sandbox Code Playgroud)

但它似乎搞砸了我的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>
Run Code Online (Sandbox Code Playgroud)

这是我的指示

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();
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

基于答案的解决方案:

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


  });
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 7

解决方案:scope从指令中删除整个属性,一切都应该按预期工作.

另外: 你需要scope从这一行重命名参数:

elem.bind('click', function(scope) {
Run Code Online (Sandbox Code Playgroud)

类似于:

elem.bind('click', function(e) {
Run Code Online (Sandbox Code Playgroud)

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

说明:

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

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