AngularJS的指令 compile和link的区别及使用示例

2025-05-10 17:49:32
推荐回答(1个)
回答1:

controller,link,compile有什么不同

//directives.js增加exampleDirective  
phonecatDirectives.directive('exampleDirective', function() {  
    return {  
        restrict: 'E',  
        template: '

Hello {{number}}!

',  
        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  
  
      
          
    
  
  

运行结果:
Hello 1111 22222 44444 55555 !

相关问答