data-ng-init执行顺序和ng-init执行顺序的区别

七步从AngularJS菜鸟到专家(4和5):指令和表达式 - 文章 - 伯乐在线
& 七步从AngularJS菜鸟到专家(4和5):指令和表达式
这一篇包含了"AngularJS – 七步从菜鸟到专家"系列的第四篇(指令)和第五篇(表达式)。
之前的几篇展示了我们应用的核心组件,以及如何设置搭建一个Angular.js应用。在这一部分,我们会厘清一些术语,然后深入探讨很多Angular.js提供的核心功能。
通过这整个系列的教程,我们会开发一个NPR(美国全国公共广播电台)广播的音频播放器,它能显示Morning Edition节目里现在播出的最新故事,并在我们的浏览器里播放它们。完成版的Demo可以看()
第四部分 指令属性
目前为止,我们已提到过几次“指令属性”的概念,但从未深入探讨过它到底是什么。实际上,“指令属性”就是绑定在DOM元素上的函数,它可以调用方法、定义行为、绑定controller及$scope对象、操作DOM,等等等等。
当浏览器启动、开始解析HTML(像平时一样)时,DOM元素上的指令属性就会跟其他属性一样被解析。
当一个Angular.js应用启动,Angular编译器就会遍历DOM树(从有ng-app指令属性的那个DOM元素开始,如我们在本系列第一篇里所提过的),解析HTML,寻找这些指令属性函数。
当在一个DOM元素上找到一个或多个这样的指令属性函数,它们就会被收集起来、排序,然后按照优先级顺序被执行。
每个指令属性都有自己的优先级,在我们关于指令属性的专题文章里(http://www.ng-newsletter.com/posts/directives.html),你可以找到更深入的信息。
Angular.js应用的动态性和响应能力,都要归功于指令属性。之前我们已经看过一些指令属性的用例:
&input ng-model="name" name="Name" placeholder="Enter your name"/&
&h4&Your name: {{ name }}&/h4&
&input ng-model="name" name="Name" placeholder="Enter your name"/&&h4&Your name: {{ name }}&/h4&
ng-model指令属性(我们在之前的章节使用过它),被用来将DOM文本输入框的值,跟controller里的$scope model绑定起来。具体的实现过程,是在这个值上绑定了一个$watch函数(类似JavaScript里的事件监听函数)。
$watch函数(在使用时)运行在Angular.js的事件循环(即$digest循环)里,让Angular.js能够对DOM进行相应的更新。请关注我们关于$digest循环的高级文章!
在Angular.js应用的开发中,我们用指令属性来将行为绑定到DOM上。指令属性的使用,是一个 应用能否拥有动态性、响应能力的关键。Angular.js提供了很多缺省的指令属性,现在让我们来看看其中几个,以及如何使用它们。
几个常见的指令属性
{{ 表达式 }}
这个双大括号指令属性,使用$watch()函数,给括号内的表达式注册了一个监听器。正是这个$watch函数,让Angular.js能够实时自动更新view。
那么,到底什么算是个表达式?
第五部分 表达式
要想理解指令属性的运作,我们必须先理解表达式,所以这里我们就绕个路,看看本系列的第五部分——表达式。在之前的例子里我们已经见过表达式,例如 {{ person.name }} 和 {{ clock }}。
{{ 8 + 1 }}9
{{ person }}{&name&:&Ari Lerner&}
{{ 10 * 3.3 | currency }}$33.00
{{ 8 + 1 }}9{{ person }}{"name":"Ari Lerner"}{{ 10 * 3.3 | currency }}$33.00
最后的例子里 (10 * 3.3 | currency) 用了一个过滤器。本系列之后的部分,会深入介绍过滤器。
表达式粗略来看有点像 eval(javascript) 的结果。它们会经过Angular.js的处理,从而拥有以下重要而独特的性质:
所有表达式都在scope这个context里被执行,因此可以使用所有本地 $scope 中的变量。
如果一个表达式的执行导致类型错误或引用错误,这些错误将不会被抛出。
表达式里不允许任何控制函数流程的功能(如if/else等条件语句)
表达式可接受一个或多个串联起来的过滤器。
试试输入“person“,“clock“或其他数学算式如2+4。你甚至可以操作scope,例如,试试输入person.name = “Ari”; person.age = 28; person 或 clock
表达式都运行在调用它们的scope里,所以一个表达式可访问并操作其scope上的一切。由此,你可以使用表达式遍历其scope的属性(我们在ng-repeat中会看到这一应用)、调用scope里的函数,或者对scope中的变量进行数学运算。
现在,让我们回到指令属性…
ng-init指令属性是一个在启动时运行的函数(在程序进入运行阶段之前)。它让我们能够在程序运行前设定初始变量的值:
JavaScript
&b ng-init='name = "Ari Lerner"'&Hello, {{ name }}&/b&
&b ng-init='name = "Ari Lerner"'&Hello, {{ name }}&/b&
Hello, Ari Lerner
ng-click指令属性给DOM元素注册了一个点击事件的监听器。当此DOM元素上有点击事件发生(即当此button或link被点击时),Angular.js就会执行表达式的内容,并相应地更新view。
&button ng-click=&counter = counter + 1&&Add one&/button&
Current counter: {{ counter }}
<button ng-click="counter = counter + 1">Add one</button>Current counter: {{ counter }}
我们也可以用ng-click 来调用在controller里写好并绑定在$scope上的函数,例如:
JavaScript
&button ng-click="sayHello()"&Say hello&/button&
&button ng-click="sayHello()"&Say hello&/button&
controller 里的函数:
JavaScript
app.controller('MyController', function($scope) {
$scope.sayHello = function() {
alert("hello!");
app.controller('MyController', function($scope) {&& $scope.sayHello = function() {&&&& alert("hello!");&& } });
ng-show / ng-hide
The ng-show and ng-hide directives show or hide a portion of the DOM depending on whether the expression is truthy.
ng-show和ng-hide指令,根据赋予它们的表达式的值的真假性(truthy),来显示和隐藏它们所属的那一部分DOM。
我们在这里不会深入,但你应该熟悉JavaScript中变量值的“truthy”和“falsy”概念。
JavaScript
&button ng-init="shouldShow = true" ng-click="shouldShow = !shouldShow"&Flip the shouldShow variable&/button&
&div ng-show="shouldShow"&
&h3&Showing {{ shouldShow }}&/h3&
&/div& &div ng-hide="shouldShow"&
&h3&Hiding {{ shouldShow }}&/h3&
&button ng-init="shouldShow = true" ng-click="shouldShow = !shouldShow"&Flip the shouldShow variable&/button& &div ng-show="shouldShow"&&& &h3&Showing {{ shouldShow }}&/h3& &/div& &div ng-hide="shouldShow"&&& &h3&Hiding {{ shouldShow }}&/h3& &/div&
ng-repeat指令遍历一个数据集合中的每个数据元素,加载HTML模版把数据渲染出来。被重复使用的模版元素,就是我们绑定了这个指令属性的DOM元素。每一个使用模版渲染的DOM元素都有自己的scope。
在更多的解释之前,我们先看一个例子。假设我们的controller里有这样一个数据元素的数组:
JavaScript
$scope.roommates = [
{ name: 'Ari'},
{ name: 'Q'},
{ name: 'Sean'},
{ name: 'Anand'}
$scope.roommates = [&& { name: 'Ari'},&& { name: 'Q'},&& { name: 'Sean'},&& { name: 'Anand'} ];
在view里我们可以用ng-repeat来遍历这个集合里的数据:
JavaScript
&li ng-repeat="person in roommates"&{{ person.name }}&/li& &/ul&
&ul&&& &li ng-repeat="person in roommates"&{{ person.name }}&/li& &/ul&
对赋予ng-repeat的表达式稍作改动,我们还可以用它遍历一个由成对的key-value数据组成的集合。例如,假设我们有一个人名和他们最喜欢的颜色的数据集合:
JavaScript
$scope.people = {
'Ari': 'orange',
'Q': 'purple',
'Sean': 'green'
$scope.people = {&& 'Ari': 'orange',&& 'Q': 'purple',&& 'Sean': 'green' }
要遍历它,我们可以给ng-repeat指令属性赋予这个表达式: (key, value) in object:
JavaScript
&li ng-repeat="(name, color) in people"&{{ name }}'s favorite color is {{ color }}
&ul&&& &li ng-repeat="(name, color) in people"&{{ name }}'s favorite color is {{ color }}&& &/li& &/ul&
Ari’s favorite color is orange
Q’s favorite color is blue
Sean’s favorite color is green
Angular.js提供的直接可用的指令属性并不多,但它让我们可以很容易地创建自己的指令属性。请到这里查看我们的指令属性创建指南:http://www.ng-newsletter.com/posts/directives.html
我们应用中的指令属性
在上一篇中,我们的收音机应用只从NPR API取回了最新的音频节目列表:
JavaScript
$scope.programs = data.list.
$scope.programs = data.list.story;
现在我们学了遍历一个list的实现方法,可以在我们的收音机应用里,像刚才那样用ng-repeat来遍历这个节目列表了:
JavaScript
&ul id="programs_list" class=""&
&li ng-repeat="program in programs"&
&span class="large-12"&{{ program.title.$text }}&/span&
&ul id="programs_list" class=""&&& &li ng-repeat="program in programs"&&&&& &span class="large-12"&{{ program.title.$text }}&/span&&& &/li&&/ul&
NPR API给我们的是一个有title+$text的列表,这个结构是NPR API所特有的,而不是Angular.js的。
现在我们列出了节目和它们的标题,但还不能点击并播放它们。用ng-click我们可以给HTML元素加上一个点击功能:
JavaScript
&ul id="programs_list" class=""&
&li ng-repeat="program in programs" ng-click="play(program)"&
&span class="large-12"&{{ program.title.$text }}&/span&
&ul id="programs_list" class=""&&& &li ng-repeat="program in programs" ng-click="play(program)"&&&&& &span class="large-12"&{{ program.title.$text }}&/span&&& &/li& &/ul&
通过这一步,我们把一个play动作函数绑定到了列表里的&li&DOM元素上。现在,我们在PlayerController里创建这个play动作函数,然后我们就有了一个功能完备的音频应用:
JavaScript
// format.mp4.$text是NPR API给我们的到这个音频mp4文件的路径 $scope.play = function(program) {
if ($scope.playing) audio.pause();
var url = program.audio[0].format.mp4.$
audio.src =
audio.play();
// 储存播放器的状态为正在播放
$scope.playing =
// format.mp4.$text是NPR API给我们的到这个音频mp4文件的路径 $scope.play = function(program) {&& if ($scope.playing) audio.pause();&& var url = program.audio[0].format.mp4.$text;&& audio.src = url;&& audio.play();&& // 储存播放器的状态为正在播放&& $scope.playing = true; }
现在这个应用功能完备了,但是还不太好看。而且随着我们继续添加新功能,代码也会膨胀,变得难以管理。我们可以创建自己的指令属性,来帮助我们减少复杂性。
想更多地学习自定义指令属性,可以看看我们深入探讨指令属性的文章:http://www.ng-newsletter.com/posts/directives.html
创建自定义指令属性,我们使用app对象的directive方法:
app.directive('nprLink', function() {
restrict: 'EA',
require: ['^ngModel'],
replace: true,
ngModel: '=',
play: '&'
templateUrl: '/views/nprListItem.html',
link: function(scope, ele, attr) {
scope.duration = scope.ngModel.audio[0].duration.$
123456789101112131415
app.directive('nprLink', function() {&& return {&&&& restrict: 'EA',&&&& require: ['^ngModel'],&&&& replace: true,&&&& scope: {&&&&&& ngModel: '=',&&&&&& play: '&'&&&& },&&&& templateUrl: '/views/nprListItem.html',&&&& link: function(scope, ele, attr) {&&&&&& scope.duration = scope.ngModel.audio[0].duration.$text;&&&& }&& } });
我们不会逐个解释每个选项的意义,因为我们有一篇专门的深入文章来介绍它们(http://www.ng-newsletter.com/posts/directives.html)。这里我们只需要明白,现在我们就能在HTML里使用这个自定义的指令属性了,它会将它所在的DOM元素替换为我们给定的templateUrl所指向的模版里的内容(在 /views/nprListItem 中)。
现在,我们的主HTML文件可以保持整洁,而将用来渲染列表内容的view,创建在这个单独提取出来的模版文件里:
&div class=&nprLink row& ng-click=&play(ngModel)&&
&span class=&name large-8 columns&&
&button class=&large-2 small-2 playButton columns&&&div class=&triangle&&&/div&&/button&
&div class=&large-10 small-10 columns&&
&div class=&row&&
&span class=&large-12&&{{ ngModel.title.$text }}&/span&
&div class=&row&&
&div class=&small-1 columns&&&/div&
&div class=&small-2 columns push-8&&&a href=&{{ ngModel.link[0].$text }}&&Link&/a&&/div&
1234567891011121314
<div class="nprLink row" ng-click="play(ngModel)">&& <span class="name large-8 columns">&&&& <button class="large-2 small-2 playButton columns"><div class="triangle"></div></button>&&&& <div class="large-10 small-10 columns">&&&&&& <div class="row">&&&&&&&& <span class="large-12">{{ ngModel.title.$text }}</span>&&&&&& </div>&&&&&& <div class="row">&&&&&&&& <div class="small-1 columns"></div>&&&&&&&& <div class="small-2 columns push-8"><a href="{{ ngModel.link[0].$text }}">Link</a></div>&&&&&& </div>&&&& </div>&& </span> </div>
注意我们在模版文件里用ngModel来指向之前的program数据,因为在创建自定义指令属性时,我们做了设置。
现在,我们在主HTML文件里就不用再写上面那么多HTML,而只要简单地换上我们的自定义指令属性npr-link:
JavaScript
&ul id="programs_list" class=""&
&li ng-repeat="program in programs"&
&span npr-link play='play(program)' ng-model="program"&&/span&
&ul id="programs_list" class=""&&& &li ng-repeat="program in programs"&&&&& &span npr-link play='play(program)' ng-model="program"&&/span&&& &/li& &/ul&
在下一章中,我们会介绍Service的用法,以及如何在我们应用的多个controller之间通讯。
本系列的官方代码库可从github上下载:
要将这个代码库保存到本地,请先确保安装了git,clone此代码库,然后check out其中的part5分支。我们使用XHR获取模版,所以你需要在本地服务器上运行这一章的代码。在part5分支里我们提供了服务器端代码:
git clone https://github.com/auser/ng-newsletter-beginner-series.git git checkout -b part5
./bin/server.sh
git clone https://github.com/auser/ng-newsletter-beginner-series.git git checkout -b part5 ./bin/server.sh
关于作者:angular.js初始化命令ng-init,ng-bind
在angular.js可以通过ng-init来初始化所需要的数据。而不需要通过其他方式再去渲染一遍。
如下代码所示:
&!DOCTYPE html&
&meta charset=&UTF-8&&
&title&Insert title here&/title&
&body ng-app ng-init=&msg='hello'&&
&p id=&app&&
&input type=&text& ng-model=&msg&&
&p&{{msg}}&/p&
&script type=&text/javascript& src=&../js/angular.js&&&/script&
打开页面之后,绑定的msg就是&&hello&&, 当需要多个变量定义时,必须用分号隔开,而不是用逗号。
当我们使用ng-bind时,在页面上看不到渲染的动作。我在应用程序中使用ng初始化一个变量。 问题是我在加载应用程序后更改了这个变量,并且我希望在函数执行后初始化变量。 我是 Angular 新手,无法找到它。这是我的ng-init:&tr ng-repeat="(script_id, cron_format) in row" **ng-init**="oldCron = cron_format"&
&td&{{user_id}}&/td&
&td&{{script_id}}&/td&
&input type="text" ng-model="cron_format" ng-blur="saveCron(user_id,script_id,cron_format,oldCron)"/&
&/tr&saveCron() 应该改变 oldCron的值,但是每次调用函数时,它都会用ng初始值初始化 oldCron 。 这是我尝试提交更改的函数:$scope.saveCron = function(userId,scriptId,cronFormat,oldCron){
if (oldCron!= cronFormat) {
oldCron = cronF
$http.post("updateCronChange.php",cron_format=" + cronFormat, function (data) {
alert('cron format changed to:' + cronFormat);
}如何在初始化之后更新 oldCron 并忽略初始化?
时间:17年08月19日原作者:
我们不能做你所需要的,因为 ng-init 在渲染HTML时被调用。你可以将变量 inside Angular 运行/配置阶段设置为 Angular,而不是这样做。代码app.run(function($rootScope, myService){
//set the variable inside $rootScope, this will available for any controller
$rootScope.myVariable = 'setFromRunPhaseUsingRootScope';
//you can use sharable service variable to set data, and use that inside your controller
myService.myVariable = 'setFromRunPhaseUsingService'
});希望这可以帮助你。
Copyright (C) 2011 HelpLib All rights reserved. &&07:42:11 UTC
Hi, i want to put value of $scope in controller into input value, this is some code.
&input type="hidden" ng-model="comment.user_email" ng-init="comment.user_email='{{post_ID}}'" value="{{post_ID}}"&&/input&
But it not works. When i use console, it shown :
Object {user_email: "{{post_ID}}"}
Not the value of post_ID.
Anybody have a solution?
20:50:43 UTC
You’re wrapping quotes around it which is telling it to set it to the string value '{{post_ID}}'.
If you want it to set to the value of post_ID you should do this:
ng-init="comment.user_email = post_ID"
You don’t need to use curly braces when inside an expression. See the .
03:30:59 UTC
thank you for reply, but it doesnt works.
The console is still
Object {user_email: “post_ID”}
Not the value of post_ID
13:24:29 UTC
Can you put together a codepen of this? I tested this in a codepen using the following:
&input ng-init="comment.email = post_ID"&
{{ post_ID }}&br&
{{ comment }}
$scope.comment = {};
$scope.post_ID = "test";
And it worked as desired.demo.html:&!DOCTYPE html&
&html lang="en"&
&meta charset="UTF-8"&
&title&AngularJS&/title&
&script src="angular.min.js"&&/script&
&!-- 引入AngularJS框架 --&
&body ng-app="App"&
&div ng-controller="DemoController" ng-init="name='张三';age=12"&
&!-- ng-init初始化,定义数据内容 --&
&h1 ng-cloak&{{name}} {{age}}&/h1&
&!-- 使用ng-init时定义的变量。ng-cloak为了避免{{}}闪烁 --&
// 创建模块
var App = angular.module('App',[]);
App.controller("DemoController",['$scope',function($scope) {
// $scope相当于MVC中的Model
// $scope.name = "张三";
// 可以通过ng-init初始化时定义name 来代替。
AngularJS 初始化指令- ng-init
ng-init 指令初始化
AngularJS 应用程序变量。
angular.js初始化命令 ng-init,ng-bind
在angular.js可以通过ng-init来初始化所需要的数据。而不需要通过其他方式再去渲染一遍。
如下代码所示:
Insert title here
AngularJS学习(二)——表达式,ng-bind,ng-app,ng-init,ng-repeat,ng-model
AngularJS的绑定:
除了用{{ }}进行绑定外,还可以使用ng-bind,比如:
HBR {{helloTo.title}}
输入您的...
ng-init的妙用
大多数人都知道ng-init里面可以放一个表达式,用来初始化当前作用域中的模型的值。
可是,今天,我想告诉大家一个ng-init的一个不一样的用法。
我先介绍一下使用该方法的一个场景:
比如,一...
angularJs中ng-if,ng-show,ng-disabled,ng-init使用案例
ng-show显示
ng-hide隐藏ng-show和ng-if的区别:ng-show是用css样式操控,ng-if是移除整个dom元素
angularJS 学习笔记2
初始化angularInit过程
整个DOMLoaded后,触发angularInit函数,执行各个模块的初始化过程。入口angularInit函数
(Angular.js L1278)function angularInit(el...
angularJS2 变量声明 var let const
变量声明let和const是JavaScript里相对较新的变量声明方式。 像我们之前提到过的,let在很多方面与var是相似的,但是可以帮助大家避免在JavaScript里常见一些问题。 const...
【Angular】Controller用来初始化作用域Scope === ng-init
没有更多推荐了,}

我要回帖

更多关于 ng-init 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信