代码之家  ›  专栏  ›  技术社区  ›  bafix2203

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

  •  0
  • bafix2203  · 技术社区  · 6 年前

    这是我的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 回复  |  直到 6 年前
        1
  •  2
  •   georgeawg    6 年前

    这个 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? .