2014-03-25 101 views
0

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

的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> 

回答

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; 
      } 
     ); 
    }; 
} 
+0

nameItems作为一个数组来自一个AJAX请求,有没有必要循环并将其转换为一个对象数组呢? – greg

+1

@greg - 是的,当然。如果你有这个限制,那么试试这个,我会更新我的答案 - http://jsfiddle.net/3FKMx/3/ –

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被用作将在角作为是外部库。

相关问题