简体   繁体   English

AngularJS:控制器中的函数被调用了三次

[英]AngularJS: Function in controller is called three times

I have a controller which calls a save service, and it is for some reason triggered three times. 我有一个调用保存服务的控制器,由于某种原因,它被触发了三次。 It is not that great if it saves three instances every time it is triggered. 如果每次触发都保存三个实例,那不是很好。 Is my approach of solving it wrong? 我解决问题的方法是错误的吗?

I found this following article which says it is a normal behavior in AngularJS 我发现以下这篇文章说这是AngularJS中的正常行为

Below is an example which triggers that behavior. 下面是触发该行为的示例。 I'm using webpack to bundle AngularJS, and other dependencies. 我正在使用webpack捆绑AngularJS和其他依赖项。

FooCtrl FooCtrl

import {IFooService} from "./FooService";

export class FooCtrl {

    static $inject = ["FooService"];

    public fooService: IFooService;

    constructor(fooService: IFooService) {
        console.log("creating foo controller");
        this.fooService = fooService;
    }

    public callService(): boolean {
        console.log("call service");
        this.fooService.save();
        console.log(this.fooService.getSaves());
        return true;
    }
}

FooService FooService

export interface IFooService {
    save(): void;
    getSaves(): number;
}

export class FooService implements IFooService{

    private saves: number = 0;

    public save(): void {
        console.log("saved");
        this.saves++;
    }

    public getSaves(): number {
        return this.saves;
    }
}

Main 主要

namespace Main {

    let fooModule = new FooModule.Module();

    let main = angular.module("myApp", [
        "ngRoute",
        fooModule.getFooModule(),
    ]);

    main.controller("BarCtrl", function($scope) {
        $scope.message = "Bar";
    });

    main.config(function($routeProvider: ng.route.IRouteProvider) {
        $routeProvider.when("/", {
            "templateUrl": "foo/index.html",
        });
    });
}

index.html index.html

<!doctype html>
<html ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="http://localhost:8080/webpack-dev-server.js"></script>
    <script src="vendors.bundle.js"></script>
    <script src="app.bundle.js"></script>
</head>
<body>
    <div ng-view></div>
</body>
</html>

index.part.html index.part.html

<div ng-controller="FooCtrl as ctrl">
    <p ng-bind="ctrl.callService()"></p>

</div>

Because you are binding your method to the <p> element, it will be trigger on every digest cycle so that angular can check if the value changed. 因为您将方法绑定到<p>元素,所以它将在每个摘要循环上触发,以便angular可以检查值是否更改。

I am not sure what you are trying to do exactly, but it looks like this this method should be trigger by a user action or maybe periodically and controlled using $timeout service. 我不确定您要尝试执行的操作,但似乎此方法应该由用户操作触发,或者应该由$timeout服务定期控制。

Read more about scope digest cycle in the official documentation . 在官方文档中阅读有关范围摘要周期的更多信息。

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

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