2016-08-02 90 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

相关问题