Page 84 - AngularJS权威教程
P. 84
64 第 9 章 内置指令
内部的代码加载之后被jQuery修改过(例如用.addClass),那么当ng-if的表达式值为false时,
这个DOM元素会被移除,表达式再次成为true时这个元素及其内部的子元素会被重新插入
DOM,此时这些元素的状态会是它们的原始状态,而不是它们上次被移除时的状态。也就是说
无论用jQuery的.addClass添加了什么类都不会存在了。
<div ng-if="2+2===5">
Won't see this DOM node, not even in the source code
</div>
<div ng-if="2+2===4">
Hi, I do exist
</div>
在线示例:http://jsbin.com/ezEcamo/1/。
7. ng-repeat
ng-repeat用来遍历一个集合或为集合中的每个元素生成一个模板实例。集合中的每个元素
都会被赋予自己的模板和作用域。同时每个模板实例的作用域中都会暴露一些特殊的属性。
$index:遍历的进度(0...length-1)。
$first:当元素是遍历的第一个时值为true。
$middle:当元素处于第一个和最后元素之间时值为true。
$last:当元素是遍历的最后一个时值为true。
$even:当$index值是偶数时值为true。
$odd:当$index值是奇数时值为true。
下面的例子展示了如何用$odd和$even来制作一个红蓝相间的列表。记住,JavaScript中数组
的索引从0开始,因此我们用!$even和!$odd来将$even和$odd的布尔值反转。
<ul ng-controller="PeopleController">
<li ng-repeat="person in people" ng-class="{even: !$even, odd: !$odd}">
{{person.name}} lives in {{person.city}}
</li>
</ul>
.odd {
background-color: blue;
}
.even {
background-color: red;
}
angular.module('myApp',[])
.controller('PeopleController',function($scope) {
$scope.people = [
{name: "Ari", city: "San Francisco"},
{name: "Erik", city: "Seattle"}
];
});
在线示例:http://jsbin.com/akuYUkey/1/edit。
8. ng-init
ng-init指令用来在指令被调用时设置内部作用域的初始状态。