参见英文答案 >
How does data binding work in AngularJS?12个
我不知道为什么叫几次.
我不知道为什么叫几次.
- <!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>');
- }
- }
- }
- });
控制台的结果是
- link
- test 1
- test 2
- test 3
这是JSFIDDLE:http://jsfiddle.net/yh9V5/
打开链接并查看console.log
解决方法
您在AngularJS中使用的所有表达式在摘要循环运行时都会多次进行评估.这是为了检查表达式的当前值是否与最后一个值不同而进行的.
请参阅“适用范围生命周期”一节了解如何发生http://docs.angularjs.org/guide/scope