Hacker
Hacker

Reputation: 7906

Directive inside a ng-repeat not working only first one seen

I have written code like below

 <div  ng-repeat="race in Races" ng-if="$index == selectedRace">
<div id="weeksOut" racedetails="race" raceday-donut></div>
</div>

And my directive looks like below

   .directive('racedayDonut', function(Donut){
    return {
        restrict: 'EA',
        transclude: true,
        scope : {
                    racedetails         : '='
                },
        replace : true,
        template : "<div></div>",
        link: function(scope)
        {
             scope.$watch('racedetails',function(newData)
            {
                var tempRaceDetails         =  newData;

                if(tempRaceDetails)
                {
                    Donut.drawDonutSvc(tempRaceDetails.weeks, tempRaceDetails.Perc, 90,'#FEFEFE', '#5b5b5b',' WEEKS OUT', 'weeksOut');
                }               
            });
        }
      };

    })

Only first directive gets drawn, but second and others are not show. when selected index changes and data changes, it comes inside but not drawn.

Upvotes: 1

Views: 296

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

Basically the problem is your are having id="weeksOut" inside ng-repeat which is repeating number of times, And its not a good practice to have same id selector multiple times on the same page. When you make query for that selector jQuery/DOM will gets confused, I might return first object.

If you really want to make your directive to make selector specific then I'd suggest generate your selector value dynamically by adding unique value with combination of weeksOut-, like tempRaceDetails has some id which tells the uniqueness of that record. So simply it would look like weeksOut-{{tempRaceDetails.id}}

Markup

<div  ng-repeat="race in Races" ng-if="$index == selectedRace">
   <div id="weeksOut-{{racedetails.id}}" racedetails="race" raceday-donut></div>
</div>

And in your directive you could use that id attribute

Donut.drawDonutSvc(tempRaceDetails.weeks, 
     tempRaceDetails.Perc, 
     90,
     '#FEFEFE', 
     '#5b5b5b',
     'WEEKS OUT', 
     'weeksOut-'+ tempRaceDetails.id //passed DOM selector name.
);

Upvotes: 2

Related Questions