迭代多个数组元素

时间:2013-12-31 06:56:24

标签: javascript html angularjs

我想迭代多个名为urls和names的数组元素。下面是只迭代url的代码。我如何使用网址名称?

JS

var app = angular.module('plunker',[]);
app.controller('Nav', function($scope) {
      $scope.names = [
          {
            "name" : "myname 1",
          },
          {
             "name": "myname 2"
          }  
      ]
      $scope.urls = [
          {
            "url" : "http://google.com",
          },
          {
             "url": "http://cnn.com"
          }
     ]; 
});

HTML

 <body ng-controller="Nav">
    {{urls}}
    {{names}}
    <div ng-repeat="link in urls">
        <input type="text" ng-model="link.url" />
        <input type="text"  />  //Want name here
    </div> 
 </body>

Plnkr:http://plnkr.co/edit/OXXdFK2JElVaAh0uYmxG?p=preview

2 个答案:

答案 0 :(得分:3)

请参阅此plunker中的答案:http://plnkr.co/edit/OhnEpFjUVfLVUQw4TP3Z?p=preview

像这样添加ng模型:

<input type="text" ng-model="names[$index].name"/>

每个ng-repeat都有一些在本地范围内公开的特殊属性,请参阅:http://docs.angularjs.org/api/ng.directive:ngRepeat

我们使用的是:

$ index - 重复元素的迭代器偏移量(0..length-1)

因此,只要两个数组具有相同的长度,这应该可以。

答案 1 :(得分:1)

您可以更改代码:

var app = angular.module('plunker',[]);
app.controller('Nav', function($scope) {
      $scope.names = [
          {
            "name" : "myname 1",
          },
          {
             "name": "myname 2"
          }  
      ]
      $scope.urls = [
          {
            "url" : "http://google.com",
          },
          {
             "url": "http://cnn.com"
          }
     ]; 
});

要     var app = angular.module('plunker',[]);     app.controller('导航',函数($ scope){           $ scope.urls = [               {                 “名字”:“myname 1”,                 “url”:“http://google.com”               },               {                  “名字”:“myname 2”,                  “url”:“http://cnn.com”               }
          ]     });

然后在你的HTML

<body ng-controller="Nav">
    <div ng-repeat="url in urls">
        <label>{{url.name}}<input type="text" ng-model="url.url" /></label>
    </div> 
  </body>

http://plnkr.co/edit/6ne9jetDZTt4QhPctUpq?p=preview