我不知道为什么会多次调用它.
<!doctype html>
<html ng-app="HelloApp">
<body>
<test-directive></test-directive>
</body>
</html>
angular.module('HelloApp', [])
.directive('testDirective', function () {
return {
restrict: 'E',
replacement: true,
template: '<div ng-class="test()">Test Directive</div>',
link : function (scope, element, attrs) {
console.log('link');
var cnt = 0;
scope.test = function () {
cnt += 1;
console.log('test', cnt);
//element.append('<h6>test' + cnt + '</h6>');
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
控制台结果是
link
test 1
test 2
test 3
Run Code Online (Sandbox Code Playgroud)
这是JSFIDDLE:http://jsfiddle.net/yh9V5/ 打开链接并查看console.log