【问题标题】:How to handle 'ng-repeat' together 'ng-model' for individual object.?如何处理单个对象的“ng-repeat”和“ng-model”。?
【发布时间】:2019-10-25 09:12:19
【问题描述】:

我有一个包含“SALARY”字段的对象数组。我想使用 ng-model 管理“信用”金额。所以我正在创建一个函数并使用对象 ID 正常工作。但在我的情况下,当我更改任何输入字段的值时,它会更改所有输入的值。

请任何人告诉我如何更改输入值只需要输入字段。

这是我的html>

<div ng-repeat="obj in myObj">
   {{obj.id}} /  
   {{obj.name}} / 
   {{obj.salary}} /
   <input type="text" ng-model="credit.amount" />
   <button ng-click="updateBalance(obj)">Balance</button>
</div> 

这是我的脚本>

 var app = angular.module('myApp',[]);
    app.controller('employee', function($scope) {
      $scope.myObj = [
        { "id" : 1, "name" : "abc", "salary" : 10000 },
        { "id" : 2, "name" : "xyz", "salary" : 15000 }
      ]

      $scope.credit = {"amount" : 0};

      $scope.updateBalance = function(obj){
        console.log(obj.name + "'s current balance is : ");
        console.log(obj.salary - Number($scope.credit.amount));
      }
});

这是我的PLNKR LINK

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    所有输入字段中的值都在发生变化,因为您将$scope.credit.amount 绑定到所有这些字段。相反,您需要单独维护它们。以下应该工作:

    HTML

    <tr ng-repeat="obj in myObj">
      <td>{{obj.id}} </td>
      <td>{{obj.name}} </td>
      <td>{{obj.salary}} </td>
      <td>
        <input type="number" ng-model="credits[obj.id].amount" />
      </td>
      <td>
        <button ng-click="updateBalance(obj)">Balance</button>
      </td>
    </tr>
    

    控制器

    var app = angular.module('myApp', []);
    
    app.controller('employee', function($scope) {
      $scope.myObj = [{
        "id": 1,
        "name": "abc",
        "salary": 10000
      }, {
        "id": 2,
        "name": "xyz",
        "salary": 15000
      }]
    
      $scope.credits = $scope.myObj.reduce(function(acc, object) {
        acc[object.id] = { amount: 0 };
    
        return acc;
      }, {});
    
      $scope.updateBalance = function(obj) {
        var balance = obj.salary - Number($scope.credits[obj.id].amount)
        alert(obj.name + ' balance is : ' + balance);
      }
    });
    

    【讨论】:

    • 但是有一个问题,就是reduce()函数在某些浏览器中不起作用。
    • 在这种情况下,.reduce 可以替换为简单的for 循环
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2015-08-13
    • 2017-11-19
    • 2012-11-22
    • 2017-09-08
    相关资源
    最近更新 更多