项目中使用了JQuery和AngularJS框架,最近定位一个问题,原因就是JQuery Ready写在了angularJS controller之前,导致JQuery选择器无法选中需要的元素(因为angularJS controller还没有初始化,dom元素的class属性没有被添加)。于是就引出了一个问题,jquery和angularjs谁先执行谁后执行的问题。当然最好我们编写的代码不要依赖于这种顺序,依赖于某些顺序的代码更容易出错。
<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之后执行的,谁在前谁先执行。