zoukankan      html  css  js  c++  java
  • (十六)JQuery Ready和angularJS controller的运行顺序问题

    项目中使用了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 autocomplete选中某项后触发事件
    Javascript类的写法
    windows2003里的数据库没被访问到
    SQL SERVER 2008 评估期已过,哪位大哥有解决方法?
    js对json增删改查操作
    javascript 谁才是initialize方法
    JavaScript的写类方式(1)
    我所收集的googlemap 应用实例
    经典的正则表达式工具Regulator使用教程(图文)
    Map的使用
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5172898.html
Copyright © 2011-2022 走看看