前端 - angular學(xué)習(xí):我的第一個自定義指令
問題描述
最近兩天看了下官方的文檔,和網(wǎng)上找到的教程,來學(xué)習(xí)angular里的自定義指令。
下面定義的指令想實現(xiàn)的功能很簡單,點擊 + - 能夠改變商品的數(shù)量
增加減少商品數(shù)量按鈕功能有些問題,還需要完善PS:寫這個指令除了想練習(xí)指令的屬性的運用,更想知道scope中的 ’=’ ’@’ ’&’怎么使用今天看了下官方文檔的講解,還是不怎么理解,所以決定寫個例子看看
寫的購物車,點擊 + - 不能改變數(shù)量?
歡迎大家批評指正吐槽!!!<!DOCTYPE html><html ng-app='myApp'> <head > <meta charset='utf-8'> <title>angular directive tab選項卡</title> <link rel='stylesheet' 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>商品數(shù)量</th> <th>增加商品數(shù)量</th> <th>減少商品數(shù)量 </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,一般用來放一個函數(shù)
相關(guān)文章:
1. 極光推送 - Android app消息推送 百度 極光 個推 信鴿哪個好一些?2. 什么是前后端分離?用vue angular等js框架就能實現(xiàn)前后分離了嗎?3. ddos - apache日志很多其它網(wǎng)址,什么情況?4. android - 百度地圖加載完成監(jiān)聽5. javascript - avalon使用:duplex設(shè)置select默認option的bug6. html - css中怎么命名顏色比較好?7. java - 為什么第一個線程已經(jīng)釋放了鎖,第二個線程卻不行?8. apache - 想把之前寫的單機版 windows 軟件改成網(wǎng)絡(luò)版,讓每個用戶可以注冊并登錄。類似 qq 的登陸,怎么架設(shè)服務(wù)器呢?9. javascript - vue 初始化數(shù)據(jù)賦值報錯10. javascript - 求根據(jù)地址查郵編的API
