2015-10-16 29 views
3

app.js是:如何理解指令優先級工作Angularjs

var app = angular.module('myApp',[]); 
app.directive('myDirective2', function() { 
    return{ 
     restrict: 'A', 
     priority: 100, 
     //template:"<h1>myDirective2</h1>", 
     controller: function ($scope, $element, $transclude,$timeout) { 
      //$scope.name = "executed myDirective2"; 
      $timeout(function() { 
       $scope.name = "executed myDirective2"; 
      }, 3000); 
     } 
    }; 
}); 

app.directive('myDirective3', function() { 
    return{ 
     restrict: 'A', 
     priority: 200, 
     //template:"<h1>myDirective3</h1>", 
     controller: function ($scope, $element, $transclude, $timeout) { 
      $timeout(function() { 
       $scope.name = "executed myDirective3"; 
      }, 3000); 
     } 
    }; 
}); 

而且index.html是:

<!DOCTYPE html> 
<html ng-app="myApp"> 
    <head> 
     <script src="js/angular.js" type="text/javascript"></script> 
     <script src="js/app.js" type="text/javascript"></script> 
    </head> 
    <body> 

     <div my-directive3 my-directive2></div> 
     <br/> 
     Name:{{name}} 

    </body> 
</html> 

儘管爲什麼找執行my-directive2優先my-directive2較小比my-directive3仍?在這種情況下,它不應該是具有更高優先級的指令,是my-directive3

回答

10

優先級是指令得到執行的數字第一個在多個優先級的情況下。基本上你用它來確定執行順序,而不是排除其他指令。

首先編譯具有更大數字優先級的指令。 預鏈接功能也按優先順序運行,但鏈接後鏈接功能按相反順序運行。具有相同優先級的 指令的順序未定義。默認優先級爲0.

您可以閱讀更多關於它here