panagulis72 panagulis72 - 1 year ago 105
jQuery Question

Repeat a directive in Angular

I have a directive which build a star icon. I want to repeat it 'n' times. And then I want to change the class in 'active' to 'n' stars.
This is the directive which build a star and, on click, it add the class 'active'.

<div ng-app="app">
<div ng-controller="ctrl">
<div class="presentation">
<button-star repeatStars="7" limitActiveStar="5" classToAdd="active"></button-star>

.directive('buttonStar', function() {
return {
scope: {
repeatStars: "=",
limitActiveStar: "=",
classToAdd: "="
restrict: 'E',
template: '<button class="btn btn-icon"><span class="glyphicon glyphicon-star"></span></button>',
link: function(scope, elem) {

So, in my example, I'd like to repeat the directive 7 times and add to the first 5 elements the class 'active'

Answer Source

Add this in your controller :

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


<button-star ng-repeat="i in getNumber(number) track by $index" repeat-stars="7" limit-active-star="5" class-to-add="{{$index < 5 ? 'active' : ''}}"></button-star>

should work

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download