2

I want to iterate over multiple array elements named urls and names. Below is the code where only urls are iterated. How can I use names also with urls?

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 Answers 2

3

See answer in this plunker: http://plnkr.co/edit/OhnEpFjUVfLVUQw4TP3Z?p=preview

Add the ng-model like this:

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

Every ng-repeat has some special properties exposed on local scope, see: http://docs.angularjs.org/api/ng.directive:ngRepeat

The one we are using is:

$index - iterator offset of the repeated element (0..length-1)

So as long as both arrays have the same length, this should work.

Sign up to request clarification or add additional context in comments.

Comments

1

Can you change the code:

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"
          }
     ]; 
});

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

then in your 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 ?

1 Comment

Thanks for the reply Marius, but that's currently not possible else would have done it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.