(十六)JQuery Ready和angularJS controller的运行顺序问题
jQuery 运行 顺序 angularjs Controller 十六 Ready 问题
2023-09-27 14:27:01 时间
项目中使用了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之后运行的,谁在前谁先运行。
相关文章
- JQuery利用sort对DOM元素进行排序
- WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)
- Jquery中针对全局快捷键和文本框(回车)快捷键的用法(实例)
- jQuery实现表格行的删除和增加(1+X Web前端开发初级 例题)
- jquery用div模拟一个下拉列表框
- Jquery - Select 和 Checkbox 、Textarea的操作
- 更好使用jQuery的8个小技巧
- MVC验证11-对复杂类型使用jQuery异步验证
- 《jQuery Cookbook中文版》——1.14 获取、设置和删除DOM元素属性
- 《jQuery UI 开发指南》——第1章 jQuery UI介绍1.1 jQuery UI的安装
- dom与jquery互相转换
- webpack中引用jQuery的四种方式
- jquery easyui datagrid 无滚动条,datagrid 没垂直滚动条
- Jquery+css实现图片无缝滚动轮播
- jquery插件
- jquery html标签的链式语法
- jquery获取checkbox状态
- 七.jQuery源码解析之.toArray()
- jQuery EasyUI之DataGrid使用示例