2016-08-02 91 views
0

有些人可以解釋爲什麼指令下面沒有被調用?如果我直接將該指令添加到按鈕,它會被調用。我嘗試使用$超時添加,但仍然沒有運氣。爲什麼使用編程方式添加角度指令時不起作用

<html>  
     <head> 
      <title>AngularJS</title> 
      <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 

      <script type="text/javascript"> 

      var app = angular.module('MyApp',[]); 

      app.controller('MyCtrl',function($scope,$timeout){ 

      document.getElementById('myBtn').setAttribute('my-directive',''); 

      }); 

      app.directive('myDirecitive',function(){ 

      function linkFn (scope,element,attrs){ 
       element.bind('click',function(){ 
        alert('Clicked'); 
       });   
      } 

      return { 
       restrict:'A', 
       link:linkFn 
      } 
      });   

      </script> 

     </head> 

     <body ng-app="MyApp", ng-controller="MyCtrl">  
      <button id="myBtn">Test</button>   
     </body> 
    </html> 
+0

指令名拼寫錯誤 –

+0

只是一個猜測,但你可能會想在閱讀了[$範圍$應用()](HTTPS:/ /docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply)。 – adamdport

+0

@adamdport我試過這樣做$ apply。它仍然不起作用。 – Ambegodas

回答

1
app.directive('myDirecitive',function(){ 

應該

app.directive('myDirective',function(){ 

最好不要來查詢控制器內部的DOM。不這樣做

document.getElementById('myBtn').setAttribute('my-directive',''); 

my-directive作爲一個屬性指令被創造了,所以這將是最好直接添加到這樣的元素。

<button id="myBtn" my-directive>Test</button> 

我創建了一個plunker

https://plnkr.co/edit/pispsMzbJIxrIDyIv81N?p=preview

+0

謝謝..這是一個錯字..但它仍然不起作用。你試過了嗎? – Ambegodas

+0

它應該現在工作。我已經創建了一個跳板 –

+0

Yap。謝謝。它的工作,如果你直接添加它,因爲我已經在問題中提到過。但是,如果我使用Java腳本添加它,這是行不通的。 – Ambegodas

相關問題