/directives.js增加exampleDirective phonecatDirectives.directive('exampleDirective', function() { return { restrict: 'E', template: '<p>Hello {{number}}!</p>', controller: function($scope, $element){ $scope.number = $scope.number + "22222 "; }, link: function(scope, el, attr) { scope.number = scope.number + "33333 "; }, compile: function(element, attributes) { return { pre: function preLink(scope, element, attributes) { scope.number = scope.number + "44444 "; }, post: function postLink(scope, element, attributes) { scope.number = scope.number + "55555 "; } }; } } }); //controller.js添加 dtControllers.controller('directive2',['$scope', function($scope) { $scope.number = '1111 '; } ]); //html <body ng-app="phonecatApp"> <div ng-controller="directive2"> <example-directive></example-directive> </div> </body>
運(yùn)行結(jié)果:
Hello 1111 22222 44444 55555 !
由結(jié)果可以看出來,controller先運(yùn)行,compile后運(yùn)行,link不運(yùn)行。
將上例中的compile注釋掉
// compile: function(element, attributes) { // return { // pre: function preLink(scope, element, attributes) { // scope.number = scope.number + "44444 "; // }, // post: function postLink(scope, element, attributes) { // scope.number = scope.number + "55555 "; // } // }; // }
運(yùn)行結(jié)果:
Hello 1111 22222 33333 !
由結(jié)果可以看出來,controller先運(yùn)行,link后運(yùn)行,link和compile不兼容。