1.首先引入angular.js和测试用到的相关js
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">
//建立模块
var app = angular.module("myApp",[]);
//创建控制器 参数1:name(控制器名称),参数2:函数
// $scope --- 控制层和视图层中交换数据的桥梁 对外访问视图可调用,直接写函数的话只能内部调用
app.controller("myController",function($scope){
//仅内部自己调用,不可用表达式调用
var addSelf = function(){};
; //对外开放,html中利用表达式可直接调用{{add}}
$scope.add = function(){
return ($scope.x)*1 + ($scope.y)*1
}
app.controller("myController",function($scope){
//普通数组
$scope.list = [1,2,3,4,5,6];
//json对象
$scope.json_list = [
{
"name":"张三",
"shuxue":"100",
"yuwen":"66"
},
{
"name":"李四",
"shuxue":"880",
"yuwen":"99"
},
{
"name":"王五",
"shuxue":"80",
"yuwen":"46"
}
]
});
});
</script>
2.常用标签
- {{}}表达式
用来获取数据,或者进行数据双向绑定;
例子:<!-- 1.ng-app 相当于angular的启动引擎 ,与js中对应 2.ng-controller:控制器 3.na-model 双向绑定,angular语法中可直接获取该变量所对应标签的内容, 4.ng-init 初始化,只在第一次执行, ng-init="name2='123' "(给相应ng-model初始化,也可调用上文中的add函数) --> <body ng-app=“myApp” ng-controller="myController" ng-init="name2='123' "> <!-- 可直接计算出结果:200--> {{100+100}} <br> <!-- 表达式中的name会和input中的值同步,因此在js中也可以随时监听同步获取 --> 请输入姓名:<input ng-model="name"> <input ng-model="name"> {{name}} <!-- 可直接获取ng-init初始化的值 --> <input ng-model='name2'> <!-- 遍历普通数组--> <ul ng-repeat="x in list"> <li>{{x}}</li> </ul> <!-- 遍历json数组 --> <table> <tr> <td>姓名</td> <td>数学分数</td> <td>语文分数</td> </tr> <tr ng-repeat="student in json_list"> <td>{{student.name}}</td> <td>{{student.shuxue}}</td> <td>{{student.yuwen}}</td> </tr> </table> </body>
3.重后台获取数据(这里自定义的json数据,改变$http.get()中的路径即可获取controller返回的数据)
例子:使用spring-boot,引入web依赖即可
结构图:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>angular内置服务</title>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script>
var app = angular.module("myApp",[]);
app.controller("myController",function($scope,$http){
$scope.getList = function(){
alert("777");
$http.get("../templates/data.json").success(
function(returnDate){
$scope.json_list = returnDate
}
);
}
})
</script>
</head>
<body ng-app="myApp" ng-controller="myController" ng-init="getList()">
<table>
<tr>
<td>姓名</td>
<td>数学分数</td>
<td>语文分数</td>
</tr>
<tr ng-repeat="student in json_list">
<td>{{student.name}}</td>
<td>{{student.shuxue}}</td>
<td>{{student.yuwen}}</td>
</tr>
</table>
</body>
</html>
data.json:
[
{
"name":"张三",
"shuxue":"100",
"yuwen":"66"
},
{
"name":"李四",
"shuxue":"88",
"yuwen":"55"
},
{
"name":"王五",
"shuxue":"89",
"yuwen":"98"
}
]