User_3535
User_3535

Reputation: 852

Repeat a div or span according to the json value using angularjs

Suppose i have a json file as

{  
   "count":"3"
}

how to show 3 span or "n" number of span according to json value

here is my Plunker url

Upvotes: 0

Views: 341

Answers (4)

Sreekanth
Sreekanth

Reputation: 3130

You could simply do this.

var app = angular.module("sampleApp", []);

app.controller("sampleController", ["$scope",
  function($scope) {

    $scope.pro = [{
      product: "chicken",
      rating: 3
    }, {
      product: "fish",
      rating: 1
    }, {
      product: "pizza",
      rating: 4
    }];

    $scope.repeat = function(rating) {
      return new Array(rating);
    }
  }
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
  <div ng-controller="sampleController">
    <div ng-repeat="array in pro">
      <div>{{array.product}}
        <span ng-repeat="number in repeat(array.rating) track by $index" ng-init="">*</span>
      </div>
    </div>
    </body>
  </div>
</div>

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

CONTROLLER

var app = angular.module('myapp',[]);
app.controller('ctrlParent',function($scope){
    $scope.count =3;    
    $scope.getNumber = function(num) {
        return new Array(num);   
    }
});

HTML

   <li ng-repeat="i in getNumber(myNumber) track by $index"><span>{{$index+1}}</span></li>

JSFIDDLE

Upvotes: 2

Linh Nguyen Vu
Linh Nguyen Vu

Reputation: 291

Not sure what you mean. But according to my view, you have 2 problems: 1. Read count in json file 2. Show n span in view.

  • To read a json file, you can create a service to get it. Follow this Reading data from JSON file in Angularjs

  • Show show those span, use ng-repeat: Hello world count is $scope variable in ur controller.

Hope this help

Upvotes: 0

Sujithrao
Sujithrao

Reputation: 785

$scope.number = 5;
$scope.getNumber = function(num) {
    return new Array(num);   
}

<ul>
<li ng-repeat="i in getNumber(number)"><span>{{$index+1}}</span></li>
</ul>

Upvotes: 0

Related Questions