首页 > 语言 > JavaScript > 正文

Angular.js初始化之ng-app的自动绑定与手动绑定详解

2024-05-06 15:13:34
字体:
来源:转载
供稿:网友

前言

众所周知在传统的angularJS应用中,都是通过ng-app把angular应用绑定到某个dom上,这样做会把js代码入侵到html上,angular提供了手动启动的API--angular.bootstrap()

本文将给大家详细介绍关于Angular.js初始化之ng-app自动与手动绑定的相关内容,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍。

一、传统的绑定初始化

<html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script></head><body ng-app="myApp"> <div ng-controller="myCtrl">  {{ hello }} </div> <script type="text/javascript">  var myModule = angular.module("myApp",[]);  myModule.controller("myCtrl",function($scope){   $scope.hello = "hello,angular!";  }); </script></body></html> 

二、手动初始化

angular.bootstrap(element, [appName], [config]);

element: 绑定ng-app的dom元素 modules:绑定的模块名字 config: 附加的配置
<html> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script><body id="body"> <div ng-controller="myCtrl">  {{ hello }} </div> <script type="text/javascript">  var app = angular.module("bootstrapTest",[]);  app.controller("myCtrl",function($scope){   $scope.hello = "hello,angular from bootstrap";  });     // angular.bootstrap(document.getElementById("body"),['bootstrapTest']);  angular.bootstrap(document,['bootstrapTest']); // 浏览器加载的每个html都会对应一个document对象, 此对象是所有html中dom元素的根节点,也属于dom元素 </script></body></html> 

注意: angular.bootstrap只会绑定第一次加载的对象,后面重复的绑定或者其他对象的绑定,都会在控制台输出错误提示

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对错新站长站的支持

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选