Angular動態(tài)添加、刪除輸入框并計算值實例代碼
摘要: 在學習群中交流時,有人分享了一個動態(tài)添加輸入框的方法,我在其基礎上進行了一些改進
這個功能本身并不復雜,但還是要注意,每個ng-model的對象必須是不同的,這樣才能把它們分隔開。
下面是完整代碼:
JS:
angular.module("myApp",[]) .controller("inputController",function($scope){ $scope.items=[]; //初始化數(shù)組,以便為每一個ng-model分配一個對象 var i=0; $scope.getResult=function(){ //計算輸入框的總值 var result=0; angular.forEach($scope.items,function(item,key){ result+=parseInt($scope.items[key]); }) $scope.result=result; } $scope.Fn= { add: function () { //每次添加都要給items數(shù)組的長度加一 $scope.items[i] = 0; i++; }, del: function (key) { //每次刪除一個輸入框都后要讓i自減,否則重新添加時會出bug console.log(key); $scope.items.splice(key, 1); i--; $scope.getResult(); //每次刪除時得重新計算總值 } } })HTML:
<body ng-controller="inputController"> <div ng-repeat="(key,item) in items track by $index"> <!-- 借助track by $index進行循環(huán)--> <input ng-model="items[key]"/><button ng-click="Fn.del(key)">刪除</button> </div>{{result}}<button ng-click="Fn.add()">Add</button> <button ng-click="getResult()">Result</button></body>應該沒有什么bug。但如果有什么更漂亮的做法,懇請大神分享一下,因為我知道這樣寫并不是很優(yōu)雅。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選