In the past two days, I have read official documents and tutorials found online to learn custom instructions in angular.
The function that the command defined below wants to achieve is very simple. Click - to change the quantity of the product
There are some problems with the button function of adding and reducing the number of products, and it needs to be improved
PS: In addition to practicing the use of the attributes of the command when writing this command, I also want to know how to use the '=' '@' '&' in the scope
I read the explanation in the official document today, but I still don’t understand it, so I decided to write an example to see
Written in the shopping cart, click - Can't change the quantity?
<!DOCTYPE html>
<html ng-app="myApp">
<head >
<meta charset="utf-8">
<title>angular directive tab选项卡</title>
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" type="text/css">
</head>
<body>
<shop-cart></shop-cart>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script type="text/javascript">
angular.module('myApp',[])
.controller('myCtrl',['$scope',function($scope){
$scope.datas = [
{name:'花生',price:14,number:1,addBtn:'+',reduceBtn:'-'},
{name:'牛奶',price:25,number:1,addBtn:'+',reduceBtn:'-'},
{name:'蛋糕',price:25,number:1,addBtn:'+',reduceBtn:'-'}
];
}])
.directive('shopCart',function() {
return {
restrict:'EA',
scope:{
onAdd:'&',
onReduce:'&'
},
templateUrl:'shop-cart.html',
controller: 'myCtrl',
link: function(scope,element,attr) {
scope.onAdd = function(num,index){
num =scope.datas[index].number + 1
scope.datas[index].number = num;
};
scope.onReduce = function(num,index){
if(num > 0) {
num =scope.datas[index].number - 1
scope.datas[index].number = num;
}
};
console.log(scope);
}
}
});
</script>
</body>
</html>
<table class="table table-striped" ng-controller="myCtrl">
<thead>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>商品数量</th>
<th>增加商品数量</th>
<th>减少商品数量 </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="data in datas">
<td>{{data.name}}</td>
<td>{{data.price}}</td>
<td ng-model="data.number">{{data.number}}</td>
<td><a ng-click="onAdd(data.number,$index)">{{data.addBtn}}</a></td>
<td><a ng-click="onReduce(data.number,$index)">{{data.reduceBtn}}</a></td></td>
</tr>
</tbody>
</table>
a=b means that the value of a is the value of variable b;
a@b means that the value of a is the string 'b';
a&b means that a refers to b, which is generally used to put a function