慕的地6264312
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()的方式调用。
BIG阳
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>