/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>
运行结果:
Hello 1111 22222 44444 55555 !
由结果可以看出来,controller先运行,compile后运行,link不运行。
将上例中的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 ";
// }
// };
// }
运行结果:
Hello 1111 22222 33333 !
由结果可以看出来,controller先运行,link后运行,link和compile不兼容。