簡體   English   中英

為什么以編程方式添加時角度指令不起作用

[英]Why angular directives are not working when added programmatically

有人能解釋一下為什么下面的指令沒有被調用嗎? 如果我直接將指令添加到按鈕,則會被調用。 我嘗試使用$ timeout添加它,但是還是沒有運氣。

<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>
 app.directive('myDirecitive',function(){

應該

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

最好不要在控制器內部查詢DOM。 不要這樣

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

my-directive是作為屬性指令創建的,因此最好將其直接添加到這樣的元素中。

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

我創造了一個矮人

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM