Brieuc
Brieuc

Reputation: 4114

AngularJs : ng-repeat with ng-if, repeating more than it should in ng-if

i need to have a list of data that is filtered by its defined property (monitored), i can't just do :

ng-if="project.monitored"

since i need to count unmonitored ones.

for the example i simplified the data returned from getProjects(), which is normally :

this.projects = {
    "owned": [
        {
            "name": "project-1",
            "monitored": true
        },
        {
            "name": "project-2",
            "monitored": true
        }
    ],
    "John Doe": [
        {
            "name": "project-3",
            "monitored": true
        },
        {
            "name": "project-4",
            "monitored": false
        }
    ]
};

I'll iterate through this.projects.owner at first then through the rest later in the template. Total of unmonitored here would be equal to 1.

So i guess i can't use such kind of solution


EXAMPLE :

template

<div ng-init="getProjects()">
    <div ng-if="vm.isMonitored(project.name)" ng-repeat="project in vm.projects">{{ project.name }}</div>  
</div>

controller :

getProjects(){

    console.log('init');

    this.projects = {
        {
            "name": "project-1",
            "monitored": true
        },
        {
            "name": "project-2",
            "monitored": true
        }
    };

}

isMonitored(name) {

    console.log('Name :'+name);

    return true;

}

template is correctly displaying 2 results :

project-1 project-2

but the console.log :

init
dashboard.controller.js?e45c:217 Name :project-1
dashboard.controller.js?e45c:217 Name :project-2
dashboard.controller.js?e45c:217 Name :project-1
dashboard.controller.js?e45c:217 Name :project-2
dashboard.controller.js?e45c:217 Name :project-1
dashboard.controller.js?e45c:217 Name :project-2

So i can't understand why i have so many duplicates from console.log while the result displayed on the template is correct.

Therefore if i count anything in ng-if, the result would be wrong. Why? Any solutions?

Upvotes: 0

Views: 150

Answers (1)

On each digest cycle, AngularJS will reevaluate the registered watchers (so your vm.isMonitored(project.name)). This is why your console show many times the log.

When you use a ng-if, the value used must be a boolean, or a method returning a boolean. You can't do business work in this method, because of the mecanism of AngularJS. To be good, your view should be :

<div ng-if="project.monitored" ng-repeat="project in vm.projects">{{ project.name }}</div>

Or even better, you could filter your collection in the controller to optimize the ng-repeat work.

Upvotes: 1

Related Questions