Angular動態添加、刪除輸入框並計算值執行個體代碼,angular輸入框

來源:互聯網
上載者:User

Angular動態添加、刪除輸入框並計算值執行個體代碼,angular輸入框

Angular動態添加、刪除輸入框並計算值執行個體代碼

摘要: 在學習群中交流時,有人分享了一個動態添加輸入框的方法,我在其基礎上進行了一些改進

這個功能本身並不複雜,但還是要注意,每個ng-model的對象必須是不同的,這樣才能把它們分隔開。

下面是完整代碼:

JS:

angular.module("myApp",[]) .controller("inputController",function($scope){    $scope.items=[];  //初始化數組,以便為每一個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數組的長度加一        $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進行迴圈-->     <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。但如果有什麼更漂亮的做法,懇請大神分享一下,因為我知道這樣寫並不是很優雅。

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.