Ambegodas
Ambegodas

Reputation: 133

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>

Upvotes: 0

Views: 69

Answers (1)

Richard Hamilton
Richard Hamilton

Reputation: 26444

 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

Upvotes: 1

Related Questions