angular中要注意的指令

时间:2023-03-09 09:56:27
angular中要注意的指令

1.ng-repeat

遍历集合,给每个元素生成模板实例,每个实例的作用域中可以用一些特殊属性,如下:

 $index    //遍历集合的下标
$first //遍历集合中的第一个对象
$last   //遍历集合中的最后一个对象
$middle //遍历集合第一个和最后一个之间的对象
$even //遍历集合的偶数对象
$odd //遍历集合的奇数对象

实例:

 <ul>
<li ng-repeat="char in
[{'alphabet': 'K'},
{'alphabet': 'A'},
{'alphabet': 'V'},
{'alphabet': 'L'},
{'alphabet': 'E'},
{'alphabet': 'Z'}] " ng-show="$even">{{char.alphabet}}</li>
</ul>

2.ng-href

href和ng-href的区别在于,ng-href默认表达式生效前不要加载该资源。

看下面的例子:

 <ul ng-init="myHref=''">
<li><a ng-href="{{ myHref }}">{{linkText}}</a></li>
<li><a href="{{ myHref }}">可以点击,但不一定是正确的地址</a></li>
</ul>
.run(function($rootScope, $timeout) {
$rootScope.linkText = '尚未加载,您无法点击';
$timeout(function() {
$rootScope.linkText = '请点击'
$rootScope.myHref = 'http://google.com';
}, 2000);
})

3.ng-src

大同小异,即表达式生效前不要加载该资源。

 <img ng-src="{{imgSrc}}"/>
.run(function($rootScope, $timeout) {
$timeout(function() {
$rootScope.imgSrc = 'https://octodex.github.com/images/daftpunktocat-guy.gif';
}, 2000);
})