【问题标题】:How to edit object properties with `ng-repeat` and `ng-model` input如何使用 `ng-repeat` 和 `ng-model` 输入编辑对象属性
【发布时间】:2018-06-03 15:45:43
【问题描述】:

这是我的 HTML:

  <div ng-repeat="n in items">

           <ul ng-repeat="(name, param) in n.params"  style="list-style-type: none;">
             <li>{{name}} : {{param}}</li>
           </ul>
       <input style="display:inline;width:130px;margin-bottom:5px;margin-top:5px;"
           class="form-control" name="text" placeholder="age"
           ng-model="age">
       <input style="display:inline;width:115px;margin-bottom:5px;margin-top:5px;" 
           class="form-control" name="text" placeholder="weight"
           ng-model="weight">
       <br />
       <button class="btn btn-warning" type="button"
           ng-click="add(n.params , age , weight)">Update</button>
 </div>

我的 JS:

$scope.items = [ 
       {
          "params": {
            "age": 22,
            "weight": 66
          }
     },
       {
          "params": {
            "age": 19,
            "weight": 54
          }
     },
       {
          "params": {
            "age": 17,
            "weight": 75
          }
    }
 ]


   $scope.add = function(params , age, weight) {
         $scope.params = params;
         if(age)
          $scope.params.age = age;
       if(weight)
          $scope.params.weight = weight;
          console.log($scope.params);
        }

我想像在我的示例中一样编辑数组,但看起来像这样:

 <ul ng-repeat="(name, param) in n.params"  style="list-style-type: none;">
    <li>{{name}} :   
        <input style="display:inline;width:130px;margin-bottom:5px;margin-top:5px;"
            class="form-control" name="text" placeholder="param"
            ng-model="param">
    </li>
 </ul>

这是我的笨蛋:http://plnkr.co/edit/h4BGIs8nPM3wZfJrwcFT?p=preview 提前谢谢解答!!!

【问题讨论】:

    标签: angularjs angularjs-ng-repeat angularjs-ng-model


    【解决方案1】:

    ng-repeat 指令创建一个子作用域,当ng-model 属性指定原语时隐藏值:

    <div ng-repeat="n in items">    
        <ul>
            <li ng-repeat="(key, value) in n.params">
              {̶{̶k̶e̶y̶}̶}̶ ̶:̶ ̶<̶i̶n̶p̶u̶t̶ ̶n̶g̶-̶m̶o̶d̶e̶l̶=̶"̶v̶a̶l̶u̶e̶"̶>̶
              {{key}} : <input ng-model="n.params[key]">
            </li>
        </ul>
    </div>
    

    遵循始终使用 '.' 的“最佳实践”,可以轻松避免原语的这个问题。在你的 ng 模型中。

    有关详细信息,请参阅What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

    【讨论】:

      猜你喜欢
      • 2012-11-22
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多