2016-01-21 51 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!'); 
       } 
      }; 
     };