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

时间:2016-06-07 15:28:01

标签: angularjs typescript

我有一个调用保存服务的控制器,由于某种原因触发了三次。如果它在每次触发时保存三个实例,那就不那么好了。我的解决方法是错误的吗?

我在article后面发现了这一点,它说这是AngularJS中的正常行为

以下是触发该行为的示例。我正在使用webpack捆绑AngularJS和其他依赖项。

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接口

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;
    }
}

主要

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

<!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

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

</div>

1 个答案:

答案 0 :(得分:1)

因为您将方法绑定到<p>元素,所以它将在每个摘要周期触发,以便angular可以检查值是否更改。

我不确定您要完全尝试做什么,但看起来这个方法应该由用户操作触发,或者可以使用$timeout服务定期控制。

在官方documentation中了解有关范围摘要周期的详情。

相关问题