Cartin
Cartin

Reputation: 13

Method fires up multiple times

I call a method in my controller, but it fires up 2 times when I want to log object.name. When I want to log whole object, it fires up 6 times. Do you know why?

(function(){

    var app = angular.module('portfolio', ['ngRoute' ]);

    app.controller('ReferenceController', function(){

        this.product = references;
        this.arrayLength = this.product.length;

        // @TODO
        this.getReferences = function(){ 

            for(var i = 0; i < this.arrayLength; i++){
                console.log(this.product[i].name);
            }

             return false;

        };

    });

    var references = [

        {
            name: "ThisIsName",
            imgUrl: "This Is Image URL",
            pageUrl: "This Is Page URL",
            tags: [
                {tag: "web"}
            ]
        }

    ];

})();

I call it like this

<div ng-controller='ReferenceController as reference'>
      {{reference.getReferences()}}
</div>

Upvotes: 1

Views: 69

Answers (2)

Some Guy
Some Guy

Reputation: 16210

This is caused by Angular's two-way data-binding which uses the $digest loop, as it is called. (Think of it as allowing Angular to check if the value has updated.) If you want to only run the function once, call it inside your controller.

You can read more about the digest loop here.

Upvotes: 2

Thinkerer
Thinkerer

Reputation: 1626

Not sure what you are asking specifically but

  for(var i = 0; i < this.arrayLength; i++){
                console.log(this.product[i].name);
            }

essentially means it will run through the entire array from start to end and for each value, it prints to the console once. So it prints multiple times for multiple values in the array.

Upvotes: 0

Related Questions