2016-11-02 45 views
-2

我想說明一個簡單的例子無法綁定在NG-重複單擊事件

var app =angular.module('myApp',[]); 
 
app.directive('callapi', function($compile, $rootScope) { 
 
    return { 
 
     restrict: 'A', 
 
     replace: false, 
 
     terminal: true, 
 
     priority: 1000, 
 
     compile: function compile(element, attrs) { 
 
      element.bind('click', function() { 
 
      alert('clicked'); 
 
      }); 
 
      return { 
 
       pre: function preLink(scope, iElement, iAttrs, controller) {}, 
 
       post: function postLink(scope, iElement, iAttrs, controller) { 
 
        $compile(iElement)(scope); 
 
       } 
 
      }; 
 
     } 
 
    }; 
 
}); 
 
app.controller('myController',function($scope){ 
 
\t $scope.simpleList = [1,2,3] 
 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app=myApp> 
 
    <div ng-controller='myController'> 
 
    <table> 
 
     <button callapi='api/user'>outerNgRepeat</button> 
 
     <tr ng-repeat='r in simpleList'> 
 
     <td>r</td> 
 
     <td>r</td> 
 
     <td><button callapi='api/user'>innerNgRepeat</button></td> 
 
     </tr> 
 
    </table> 
 
    </div> 
 
</div>

,但有一個問題 enter image description here

我不得不嘗試綁定單擊事件在指令中的元素上,但它在ng-repeat時不起作用。 如何綁定點擊ng-repeat中的元素?

+1

的截圖代碼不適合問一個問題 – Phil

+0

請提供代碼,而不是截圖 – Nitheesh

+0

對不起這個,但我在jsfiddle代碼中得到了另一個問題.... –

回答

1

您不希望在compile階段綁定ng-repeat區塊內的事件。
實際上,我認爲您在該指令的compile階段沒有任何事情要做:我想你應該簡單地使用link回調。

此外,錯誤您可以:

最大調用堆棧大小超過

...使用$compile,在你的指令中post -link勾指的是你(遞歸) 。

看看我的代碼片斷如下,從你的更新:

var app = angular.module('myApp', []); 
 
app.directive('callapi', function($compile, $rootScope) { 
 
    return { 
 
    restrict: 'A', 
 
    replace: false, 
 
    terminal: true, 
 
    priority: 1000, 
 
    link: function(scope, element) { 
 
     element.bind('click', function() { 
 
     console.log('clicked: ' + scope.r); 
 
     }); 
 
    } 
 
    }; 
 
}); 
 

 
app.controller('myController', function($scope) { 
 
    $scope.simpleList = [1, 2, 3]; 
 
});
table { 
 
    border: 1px solid black; 
 
    border-collapse: collapse; 
 
} 
 

 
tr:not(:last-child) { 
 
    border-bottom: 1px solid #ddd; 
 
} 
 

 
tr:hover { 
 
    background-color: #f5f5f5; 
 
} 
 

 
th, td { 
 
    padding: 2px 15px; 
 
    text-align: left; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app=myApp> 
 
    <div ng-controller='myController'> 
 
    <table> 
 
     <button callapi='api/user'>outerNgRepeat</button> 
 
     <tr ng-repeat='r in simpleList'> 
 
     <td>r</td> 
 
     <td>r</td> 
 
     <td> 
 
      <button callapi='api/user'>innerNgRepeat</button> 
 
     </td> 
 
     </tr> 
 
    </table> 
 
    </div> 
 
</div>

+0

但爲什麼它不能在編譯工作(因爲我需要judje用戶的auth befor按鈕出現取決於callapi ='url')。 –