猿问

AngularJs中ng-controller下的函数在调用时为什么会执行两次 ?

AngularJs中ng-controller下的函数在调用时为什么会执行两次 


守着一只汪
浏览 989回答 1
1回答

慕盖茨4494581

123456789101112131415161718192021222324252627282930313233343536373839<!doctype html><html><head><meta charset="utf-8"><title>test</title><script src="angular.min.js"></script><script>var myApp = angular.module("myApp", []);myApp.directive('testIt',function(){return {restrict: 'A',scope: false,link:function(scope, elm, attr){if(scope.$last){elm.css('color','red');scope.myFunction();}}}});myApp.controller("testCtrl", function($scope){$scope.items = [0,1,2,3,4];$scope.myFunction = function(){console.log('Hello!');};});</script></head><body><div ng-app="myApp"><div ng-controller="testCtrl"><ul><li ng-repeat="item in items" test-it >{{item}}</li></ul></div></div></body></html>主要在于12行的scope:false,这个是默认的,其实你不写也是false。这样drective继承了父scope,所以可以调用父作用域的方法,而声明新的scope即scope:{}形式就不会继承了,不过你依然可以用scope.$parent.myFunction()的方式调用。
随时随地看视频慕课网APP

相关分类

AngularJS
我要回答