前端 - angular学习:我的第一个自定义指令
问题描述
最近两天看了下官方的文档,和网上找到的教程,来学习angular里的自定义指令。
下面定义的指令想实现的功能很简单,点击 + - 能够改变商品的数量
增加减少商品数量按钮功能有些问题,还需要完善PS:写这个指令除了想练习指令的属性的运用,更想知道scope中的 ’=’ ’@’ ’&’怎么使用今天看了下官方文档的讲解,还是不怎么理解,所以决定写个例子看看
写的购物车,点击 + - 不能改变数量?
欢迎大家批评指正吐槽!!!<!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 - 1scope.datas[index].number = num; } }; console.log(scope); }} }); </script> </body></html>下面是引入模板的html
<table 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>
问题解答
回答1:a=b 表示 a 的值取 变量 b 的值;a@b 表示 a 的值是 ’b’ 这个字符串;a&b 表示 a 引用 b,一般用来放一个函数
相关文章:
1. win10系统 php安装swoole扩展2. html按键开关如何提交我想需要的值到数据库3. PHPExcel表格导入数据库怎么导入4. index.php错误,求指点5. html5和Flash对抗是什么情况?6. vue.js - Vue 如何像Angular.js watch 一样监听数据变化7. 关于Java引用传递的一个困惑?8. javascript - bootstrap table固定列之后宽度无法对齐怎么解决?9. html5 - 我引用的是花瓣网上的图片,在自己电脑上可以正常显示(状态码200),但在别人电脑上是403forbid,有大神知道是什么吗?10. 我毕业以后在工作之余学了 PHP,都是自学 现在在找这方面的工作 求前辈指导学习方向 工作常用的知识
