2016-01-21 50 views
0

我有以下指令:角指令:編譯被調用,而不是鏈接

angular.module('myModule', []).directive('myDir', function() { 
    return { 
    scope: {}, 
    restrict: 'E', 
    link: function() { 
     alert('hello!'); 
    } 
    }; 
}); 

而且我用它在模板中像這樣:

<my-dir attr1="hello" attr2="world" /> 

當我加載頁面,我沒有得到警報。但是,如果我只是分配compile屬性而不是link屬性,則會收到警報。爲什麼它不調用我的link函數,但它很高興地調用compile

注:我甚至試圖從compile函數返回一個pre/post鏈接對象,但它仍然不會調用任何東西。如果我將<my-dir>自動關閉(如上所述)也沒有關係。

+0

我試過相同的代碼,但它使用相同的代碼,我不確定它爲什麼不適合你 – vpsingh016

回答

1

相同的代碼爲我工作檢查此

<html> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script> 
    <script type="text/javascript"> 
    var myApp = angular.module('myApp',[]).directive('myDir', function() { 
     return { 
     scope: {}, 
     restrict: 'E', 
     link: function() { 
      alert('hello!'); 
     } 
     }; 
    }); 
    </script> 
<body ng-app="myApp"> 
    <my-dir attr1="hello" attr2="world" /> 
</body> 

0

能否請您試試這個。

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

     app.directive('myDir', myfunc); 

     function myfunc() { 
      return { 
       scope: {}, 
       restrict: 'E', 
       link: function() { 
        alert('hello!'); 
       } 
      }; 
     };