欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Angular動(dòng)態(tài)添加、刪除輸入框并計(jì)算值實(shí)例代碼

 更新時(shí)間:2017年03月29日 14:56:30   作者:lee1994522  
這篇文章主要介紹了Angular動(dòng)態(tài)添加、刪除輸入框并計(jì)算值實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下

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ì)象必須是不同的,這樣才能把它們分隔開。

下面是完整代碼:

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)該沒有什么bug。但如果有什么更漂亮的做法,懇請(qǐng)大神分享一下,因?yàn)槲抑肋@樣寫并不是很優(yōu)雅。

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論