angular是一个新兴的JS框架,和以往的框架不同的事,Angularjs更注重于js的建模,管理,同时也提供大量的组件帮助用户组建商业化程序,是一种值得研究的JS框架。
Angularjs使我们可以使用MVC的模式来写JS。Angularjs现在由谷歌来维护。
这里我们来简单的探讨一下它的应用。
首先使用Angularjs我们必须引入他的JS文件。
<script src="../angular.min.js"></script>
这个文件我上传到了附件中了。
Angular的主要部分包括:
ng-app :AngularJS程序入口,对该标签内的元素进行初始化。
ng-controller :在当前元素范围内绑定指定的控制器(controller)。
ng-model :指定当前元素与数据模型($scope)中的属性绑定,如果数据模型中没有此属性,会自动新建一个。
ng-repeat:循环$scope中的属性,类似于{{#each beans}}
{{xxx}}:花括号表示读取某一属性值
filter、orderBy :过滤器。filter可以根据指定的属性过滤数据(例子里是quer属性)。orderBy是排序过滤器。这两个过滤器都是内置的。过滤器是可自定义的。 我们来看一下例子:
<!doctype html>
<html >
<head>
<meta charset="UTF-8">
<script src="../angular.min.js"></script>
<script>
var StudentListCtrl = ['$scope', '$http',
function($scope, $http) {
$http.get('json/students.json')
.success(function(data) {
$scope.students = data;
});
$scope.sortType = 'age';
}
];
</script>
</head>
<body ng-app ng-controller="StudentListCtrl">
<input ng-model="quer"/>
<select ng-model="sortType">
<option value="name">
按名字排序</option>
<option value="id">
按学号排序</option>
</select>
<ul>
<li ng-repeat="student in students
| filter:quer | orderBy:sortType">
{{student.name}}
<p>{{student.sex}}</p>
<p>{{student.age}}</p>
<p>
<img ng-src="{{student.img}}"/>
</p>
</li>
</ul>
</body>
</html>
其中students.json的内容为:
[
{
"age": 13,
"id": "0001",
"name": "陈大虾",
"sex": "男",
"img":"im"
},
{
"age": 14,
"id": "0002",
"name": "陈大锅",
"sex": "男"
},
{
"age": 15,
"id": "0003",
"name": "邓小娇",
"sex": "女"
}
]
显示的结果为:
-
陈大虾
男
13
-
陈大锅
男
14
-
邓小娇
女
15
在这个例子里面,我们改变下拉框的内容,则列表显示的结果会有变化,这就是Angular的方便之处,我们只需要文件,建模的内容,而动态内容的js实现已经不需要我们来实现了。
关于在Angular设置类名:
1. 直接使用 class="{{className}}"
2. 使用ng-class="{true:'selected'}[selected]"