0
我有一個控制器調用一個保存服務,它由於某種原因被觸發三次。如果每次觸發時都保存三個實例,那就不是那麼好。我的解決方法是錯誤的嗎?AngularJS:在控制器中的功能被稱爲三次
我發現這個以下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>
它只是用於測試目的,我使用'{{}}'之前也產生了相同的錯誤。但我發現爲了測試目的,我應該使用'ng-click',這也適用於我的實現用例。 – starcorn
'{{}}'和ng-bind具有相同的效果,angular必須去檢查值是否改變,並且HTML應該被重新渲染。 'ng-click'是有道理的 –