简体   繁体   中英

Why angular directives are not working when added programmatically

Can some body explain me why below directive is not getting called? Its getting called if I directly add the directive to the button. I tried it adding using $timeout but still no luck.

<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(){

should be

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

it's best not to query the DOM inside the controller. Don't do this

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

my-directive was created as an attribute directive, so it would be best to add that directly to the element like this.

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

I created a plunker

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM