简体   繁体   English

方法多次触发

[英]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. 我在控制器中调用了一个方法,但是当我想记录object.name时,它会触发2次。 When I want to log whole object, it fires up 6 times. 当我想记录整个对象时,它将触发6次。 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>

This is caused by Angular's two-way data-binding which uses the $digest loop, as it is called. 这是由Angular的双向数据绑定引起的,该绑定使用$digest循环,即所谓的$digest循环。 (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. (将其视为允许Angular检查值是否已更新。)如果只想运行一次函数,请在控制器内部调用它。

You can read more about the digest loop here . 您可以在此处阅读更多有关摘要循环的信息

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. 因此,它将为数组中的多个值多次打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM