Call method Inside ng-repeat Loop

Viewed 106

I'm trying to simply call a method inside the ng-repeat but the element does not exist when I call it. I don't understand why or how can I fix it...

The id is correct. If I run in the dev console after it loads, it works

$scope.buildAchievementLineFill = (achievement) => {
    console.log($('#achievement-progress-' + achievement.achievementId)); // This is empty
    $('#achievement-progress-' + achievement.achievementId).xmlinefill({
        width: 150,
        percent: achievement.unlocked ? 100 : 0,
        fillWidth: 6,
        gradient: true,
        gradientColors: ['#10fac0', '#1cbdf9'],
        speed: 2,
        outline: true
    });            
}
<div class="badges-showcase-item column" ng-repeat="achievement in achievements">  
    <div class="badge-progress"
         id="achievement-progress-{{achievement.achievementId}}"
         ng-init="buildAchievementLineFill(achievement);">
    </div>
</div>

Why the id does not exist when I call the method in the ng-init?? How can I solve this problem?

2 Answers

Try after replacing your code with below one

<div class="badges-showcase-item column" ng-repeat="achievement in achievements">  
    <div class="badge-progress" id="achievement-progress-{{achievement.achievementId}}" ></div>
    {{ buildAchievementLineFill(achievement) }}
</div>

Frankly, I would put that function in a directive:

app.directive("buildLineFill", function() {
    return {
        link: postLink
    };
    function postLink(scope, elem, attrs) {
        console.log(scope.$eval(attrs.buildLineFill));
        var achievement = scope.$eval(attrs.buildLineFill);
        elem.xmlinefill({
            width: 150,
            percent: achievement.unlocked ? 100 : 0,
            fillWidth: 6,
            gradient: true,
            gradientColors: ['#10fac0', '#1cbdf9'],
            speed: 2,
            outline: true
        });            
    }
})

Usage

<div class="badges-showcase-item column" ng-repeat="achievement in achievements">  
    <div class="badge-progress"
         id="achievement-progress-{{achievement.achievementId}}"
         build-line-fill="achievement">
    </div>
</div>

It is less of a hack to do it as a directive.

For more information, see

Related