ng-app属性是angular.js的标志语句,它标记了angular.js的作用域。ng-app可以添加在很多地方,像上面那样添加到html标签上,说明angular脚本对整个页面都起作用。也可以在局部添加ng-app属性,比如在某一个div内添加ng-app,则表明接下来的整个div区域使用angular脚本解析,而其他位置则不适用angular脚本解析。
<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/angular1.0.1.min.js"></script>
</head>
<body>
Your name: <input type="text" ng-model="yourname" placeholder="World">
Hello {{yourname || 'World'}}!
</body>
</html>
ng-model表示建立一个数据模型。这里在input输入姓名的输入框内,我们把该定义了一个yourname数据模型。定义了该模型后,我们可以在下面进行调用,方法是利用{{}}。这样就完成了数据绑定,当我们在输入框内输入内容时,会同步到下面的Hello语句块中。
ng-model定义的数据模型不仅可以用于上述场景,还能在许多情况下得到广泛应用。
ng-repeat属性
ng-repeat主要用于循环输出列表。
<html ng-app="myApp">
<head>
<title>angularjs-demo</title>
<script type="text/javascript" src="angular.min.js"
charset="utf-8"></script>
</head>
<body ng-controller="ctrl">
<table width="100%" border="1" cellspacing="0"
cellpadding="0">
<tr>
<th>学号</th>
<th>姓名</th>
<th>分数</th>
</tr>
<tr ng-repeat="item in items">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.score}}</td>
</tr>
</table>
<script>
var app = angular.module('myApp',[]);
app.controller("ctrl",function($scope,$location){
$scope.items = getStu();
});
function getStu() {
return [{id:1010,name:'张三',score:50},{id:1011,name:'李四',score:60},{id:1012,name:'王五',score:80}];
}
</script>
</body>
</html>
在ng-repeat中使用$index需要注意。添加使用过滤器过滤后的索引和原始索引不一致,在对列表做移出操作等的时候,使用索引会出现问题。
<ul ng-controller="ListCtrl">
<li ng-repeat="item in items">
{{item.name}}
<button ng-click="remove($index)">remove</button>
</li>
</ul>
对应的控制器:
app.controller('ListCtrl',
['$scope', function($scope) {
$scope.items = getItems();
$scope.remove = function(index) {
var item = $scope.items[index];
removeItem(item);
}; }]);
其问题在于 $scope.items[index];
解决办法如下:
这里将 remove($index) 改成 remove(item), 并修改了 $scope.remove 函数来直接操作传过来的对象。
<ul ng-controller="ListCtrl">
<li ng-repeat="item in items | searchFilter">
{{item.name}}
<button ng-click="remove(item)">remove</button>
</li>
</ul>
控制器如下所示:
$scope.remove = function(item) {
removeItem(item);
};
ng-model 在ng-repeat中的运用
1、设置filter,实现搜索功能
在下面的代码中,我们利用一个简单的数据模型定义+filter就可以完成一个列表搜索功能。(这是中文网上的实例代码,先不需要管不清楚的部分)
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
Search: <input ng-model="query">
</div>
<div class="span10">
<ul class="phones">
<li ng-repeat="phone in phones | filter:query">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</div>
</div>
</div>
上述代码中,为搜索框的input标签绑定了数据模型query。这样,用户输入的信息会被同步到query数据模型中。在下面的li中,使用filter:query就可以实现列表中的数据过滤功能,按照用户的输入信息进行filter过滤。
2、设置orderBy,实现列表排序功能
在下面的代码中,与filter同理,使用orderBy为列表添加一个排序功能:
Search: <input ng-model="query">
Sort by:
<select ng-model="orderProp">
<option value="name">Alphabetical</option>
<option value="age">Newest</option>
</select>
<ul class="phones">
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
声明:本文部分示例来自网络,再此感谢示例原创们的辛苦奉献。