2013-05-17 37 views
6

我在想這應該很簡單,但我錯過了一些東西。如何將我的ng-repeat中的flowObj通過我的指令?我想將它傳遞給我的指令,然後點擊使用FlowObj然後應用一些邏輯。我嘗試使用我的指令中的註釋代碼AngularJs將HTML中每個ng-repeat的實例傳遞給指令

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


    }); 

回答

7

SOLUTION:從你的指令,一切刪除整個scope財產應該像exp一樣工作ected。

ALSO: 你需要的scope參數從該行重命名:因爲你在你活動覆蓋到scope訪問

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

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

喜歡的東西處理程序通過使用相同的名稱。

說明:

ng-repeat指令導致它的每一個克隆擁有自己的新範圍。由於默認情況下,元素上的指令共享作用域,所以與ng-repeat並排放置的任何其他指令都會共享其作用域,並可以訪問當前迭代的$scope變量。換句話說,您的自定義指令已經與ng-repeat共享範圍,默認情況下可以訪問flowObj

上的自定義指令指定scope屬性時,它不工作的原因是,這引起了指令具有不與ng-repeat分享,所以你沒有訪問變量在克隆自己的分離範圍'範圍。

相關問題