更新ng中的字段根据同一索引中的另一个字段重复

时间:2014-03-25 20:04:05

标签: angularjs

我希望能够在ng-repeat循环中填充文本输入字段,并在单击按钮时使用相同循环索引中的另一个字段的值。

JSFiddle我到目前为止:http://jsfiddle.net/3FKMx/

单击Copy Names按钮时,我希望每个文本框都填充与数组中相同的值。目前,它使用数组中最后一项的值填充它们。

控制器:

var app = angular.module('myApp', []);

function someController($scope) {
  $scope.names = ["name1","name2","name3"];

    $scope.copyNames = function() {
      angular.forEach($scope.names,
        function (value){
          $scope.newName = value;
        }
      );
    };

}

模板:

<div ng-controller="someController">
    <button class="btn btn-primary" ng-click="copyNames()">Copy Names</button>

    <table>
        <tr ng-repeat="name in names">
          <td>{{name}}</td>

          // I want to populate this input with {{ name }} when I click the button above.
          <td><input type="text" ng-model="newName"/></td>
        </tr>
    </table>
</div>

2 个答案:

答案 0 :(得分:1)

Solution 1

使用更新的数据结构,它可以更好地循环。

Solution 2

创建一个新数组来存储值。按键设置它们,然后用花括号中的键查找它们。

<强> HTML

<div ng-controller="someController">
    <button class="btn btn-primary" ng-click="copyNames()">Copy Names</button>

    <table>
        <tr ng-repeat="name in names">
          <td>{{name}}</td>
          <td><input type="text" ng-model="models[name]"/></td>
        </tr>
    </table>
</div>

<强>的JavaScript

var app = angular.module('myApp', []);

function someController($scope) {
    $scope.names = ["name1","name2","name3"];
    $scope.models = {};

    $scope.copyNames = function() {
        angular.forEach($scope.names,
            function (value, key) {
                $scope.models[value] = value;
            }
        );
    };
}

答案 1 :(得分:1)

你正在寻找

DEMO (更新你的小提琴)?

尝试使用对象来保存标签和模型:

$scope.names = [{label: "name1", model: ''},
                {label: "name2", model: ''},
                {label: "name3", model: ''}];


//Also using jQuery.each to break from the loop 
//once we know which value to copy
$scope.copyNames = function() {
   $.each($scope.names,
      function (i, value){
          if(value.model) {
            angular.forEach($scope.names, function(name){
                name.model = value.model;
            });

            //Break the loop if done copying
            return false;
         }
      }
   );
};

注意:jQuery用作外部库,可以按角度使用。