如何使用`ng-repeat`和`ng-model`输入编辑对象属性

时间:2018-06-03 15:45:44

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

这是我的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 感谢您提前解答!!!

1 个答案:

答案 0 :(得分:2)

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>

通过遵循&#34;最佳实践&#34;可以很容易地避免使用原语这个问题。总是有一个&#39;。在您的ng模型中。

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