AngularJS主要适用于开发CRUD的项目和单页应用程序。
1、AngularJS的特点:
- 基于MVC
- 双向数据绑定
- 依赖注入
2、AngularJS和JQuery的区别:
JQuery的特点擅长DOM操作,及对HTML的增删改查;
AnularJS擅长于数据操作,即数据的增删改查;
3、简述在AngularJS中,如何实现双向数据绑定?
在AngularJS中,有一种“脏值检查”的机制,“在脏值检查”机制中,会对ng-*指令{{}}的内容进行脏值检查
简单购物车代码示例(实现数据的双向绑定)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/angular-1.6.9.min.js"></script>
</head>
<body ng-app="myapp" ng-controller="myctrl">
<table class="table table-hover">
<tr>
<th>序号</th>
<th>名称</th>
<th>价格</th>
<th>数量</th>
<th>小计</th>
</tr>
<tr ng-repeat="x in data">
<td>{{x.id}}</td>
<td>{{x.name}}</td>
<td>{{x.price}}</td>
<td>
<input type="button" value="-" class="btn btn-xs btn-primary" ng-click="jian($index)" />
<input type="text" value="{{x.num}}" />
<input type="button" value="+" class="btn btn-xs btn-primary" ng-click="x.num=x.num+1" />
</td>
<td>{{x.num*x.price}}</td>
</tr>
</table>
<h1>总共{{getallcount()}}件商品,总计{{getMoney()}}元</h1>
</body>
<script type="text/javascript">
var app = angular.module('myapp', []);
app.controller('myctrl', function($scope) {
$scope.data = [{
id: 10,
name: '荣耀8',
price: 1500,
num: 3
},
{
id: 12,
name: '荣耀9',
price: 1400,
num: 2
},
{
id: 33,
name: '荣耀X',
price: 1800,
num: 1
},
{
id: 44,
name: '小米8',
price: 1900,
num: 7
},
{
id: 25,
name: '小米9',
price: 2200,
num: 8
},
{
id: 76,
name: 'OPPO R17',
price: 3500,
num: 5
}
]
//修改数量
$scope.jian = function(n) {
$scope.data[n].num--;
if($scope.data[n].num == 0) {
// 如果数量为0,就删除当前商品
if(window.confirm('是否要删除此商品'))
$scope.data.splice(n, 1);
}
}
// 求总数量
$scope.getallcount = function() {
var count = 0;
for(var i = 0; i < $scope.data.length; i++) {
count += $scope.data[i].num * 1;
}
return count;
}
$scope.getMoney = function() {
var money = 0;
for(var i = 0; i < $scope.data.length; i++) {
money += $scope.data[i].num * $scope.data[i].price;
}
return money;
}
})
</script>
</html>