Angular ng-repeat and dynamic properties

I have a php object that I pass to ng through a function. This object has several properties such as : paragraphe1, paragraphe2, paragraphe3 up to 8.

I try to display it with a ng-repeat loop like :

<div ng-repeat="i in [1,2,3,4,5,6,7,8]">
Paragraphe {{i}} >> {{paragraphe+i}}
</div>

It shows :

instead of the content of paragraphe1, ....8

Thanks for your help. FX

Upvotes: 0

Views: 429

Answers (2)

Murali K
Murali K

Reputation: 393

Instead of passing the values hard coded you can make use of key, value pairs in the ng-repeat

view:

<div ng-app="myApp" ng-controller="demoCtrl">
  <div ng-repeat="(key, value) in paragraph">
    {{key}} >> {{value}}
  </div>
</div>

JS:

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

// filter
app.filter('dayFilter', function() {
  return function(input) {
    var filterFunction = function (item) {
        return item.days >= 1 && item.days <= 7;
    };
    return input.filter(filterFunction);
  };
});

//controller
app.controller('demoCtrl', function ($scope) {
  $scope.paragraph = {
    paragraph1: 'lorem ipsum 1',
    paragraph2: 'lorem ipsum 2',
    paragraph3: 'lorem ipsum 3'
  }
});

Upvotes: 1

Michel
Michel

Reputation: 28239

Assuming your paragraph definition is:

$scope.paragraph = {
    paragraph1: 'lorem ipsum 1',
    paragraph2: 'lorem ipsum 2',
    paragraph3: 'lorem ipsum 3',
    // ...
}

The template should look like:

<div ng-repeat="i in [1,2,3,4,5,6,7,8]">
    Paragraphe {{i}} >> {{paragraph['paragraph' + i]}}
</div>

See js fiddle

Upvotes: 1

Related Questions