项目中使用了JQuery和AngularJS框架,近期定位一个问题,原因就是JQuery Ready写在了angularJS controller之前,导致JQuery选择器无法选中须要的元素(由于angularJS controller还没有初始化,dom元素的class属性没有被加入)。于是就引出了一个问题,jquery和angularjs谁先运行谁后运行的问题。当然最好我们编写的代码不要依赖于这样的顺序,依赖于某些顺序的代码更easy出错。
<html>
<head>
<script src="jquery-1.10.2.js"></script>
<script src="angular-1.2.2/angular.js"></script>
<script>
$(function(){
printLogAndWait("first jquery ready.");
}); $(function(){
printLogAndWait("second jquery ready.");
}); // 创建moudle1
var rootMoudle = angular.module('module', []);
rootMoudle.controller("root_controller",function($scope){
printLogAndWait("in angular controller.begin");
$scope.name="";
$scope.list = [{name:1},{name:2}];
printLogAndWait("in angular controller.end");
}); $(function(){
printLogAndWait("jquery ready right before angular.");
}); angular.element(document).ready(function() {
printLogAndWait("angular ready.begin");
angular.bootstrap(document.getElementById("root_div"),["module"]);
printLogAndWait("angular ready.end");
}); $(function(){
printLogAndWait("jquery ready right after angular.");
}); console.log("I am first execute."); function printLogAndWait(log, milliseconds)
{
console.log(log);
if(!milliseconds)
{
milliseconds = 200;
} var begin = new Date().getTime();
var end = begin; while(end - begin < milliseconds)
{
end = new Date().getTime();
}
}
</script>
</head> <body id="root">
<div id="root_div" ng-controller="root_controller"></div>
</body>
</html>
输出结果例如以下:
I am first execute.
first jquery ready.
second jquery ready.
jquery ready right before angular.
angular ready.begin
in angular controller.begin
in angular controller.end
angular ready.end
jquery ready right after angular.
能够看到:JQuery Ready和angularJS controller都是在domready之后运行的,谁在前谁先运行。