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