【发布时间】:2015-04-02 23:57:12
【问题描述】:
我正在试用 AngularJS,并且正在尝试使用 TypeScript 类为大型项目做好准备。我遇到的问题是控制器类的this 没有绑定到ng-controller 指令所在的DOM 部分内的范围。
从以下 TypeScript 代码开始:
angular.module('testApp')
.controller('TypeScriptController', () => new TypeScriptController())
// Controller implementation via TypeScript
class TypeScriptController {
text = "Please click the button";
constructor() {}
buttonClick () {
this.text = "The button was clicked";
}
}
并使用
将控制器绑定到 DOM<main ng-controller="TypeScriptController as TSCtrl">
如果我使用标准的 ES5 函数样式来实现它,它可以正常工作(参见下面的代码 sn-p 的前半部分)。但是类版本没有。现在我可以将$scope 变量传递给控制器并将$scope 的属性绑定到this 但随后HTML 中的controllerAs 语法将被忽略。但是,我想避免将$scope 传递给每个控制器。
我知道 AngularJS 1.3 为指令引入了 bindToController 选项,但我不知道如何在这种情况下应用它。
示例:
在这个例子中展示了控制器的 ES5 和 TypeScript 实现。控制器只包含一个方法,ng-click 调用该方法在按钮下方写入文本。 ES5 版本有效。 TypeScript 版本没有。我也在Plunker
angular.module('testApp', [])
.controller('MainController', MainController);
function MainController() {
this.text = "Please click the button";
this.buttonClick = function() {
this.text = "The button was clicked";
};
};
// Compiled from TypeScript source
angular.module('testApp').controller('TypeScriptController', function() {
return new TypeScriptController();
});
// Controller implementation via TypeScript
var TypeScriptController = (function() {
function TypeScriptController() {
this.text = "Please click the button";
}
TypeScriptController.prototype.buttonClick = function() {
this.text = "The button was clicked";
};
return TypeScriptController;
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="testApp">
<main ng-controller="MainController as mainCtrl">
<h1>Hello World!</h1>
<p>
<input type="button" name="testInput" value="Test button" ng-click="mainCtrl.buttonClick()">
</p>
<p>{{mainCtrl.text}}</p>
</main>
<main ng-controller="TypeScriptController as TSCtrl">
<h1>Hello TypeScript!</h1>
<p>
<input type="button" name="testInput" value="Test button" ng-click="TSCtrl.buttonClick()">
</p>
<p>{{TSCtrl.text}}</p>
</main>
</body>
【问题讨论】:
标签: angularjs typescript