在 AngularJS 应用程序中,函数内部又位于 Controller 内部, 创建变量时最好的方法是什么。
通常使用
var
关键字创建function getAnswer() { //Some code here var persistedDateValue = templateFactory.getAnswer(ctrl.item.ItemId); //Some other code here return persistedDateValue; }
将其添加到 Controller 范围
function getDateAnswer() { //Some code here ctrl.persistedDateValue = templateFactory.getAnswer(ctrl.item.ItemId); //Some other code here return ctrl.persistedDateValue; }
这里 ctrl
是 Controller ,就像 Directive controllerAs: 'ctrl',
中一样。
我的理解是,选项一更好,因为除了这个函数之外我们不需要这个变量。
请提出建议。
最佳答案
我同意 ZSnake 的回答,但是如果您确实需要在 View 上的 Controller 的其余部分中提供此变量,那么您将需要
.controler('ControllerName', function() {
var _this = this;
function getDateAnswer() {
//Some code here
_this.persistedDateValue = templateFactory.getAnswer(ctrl.item.ItemId);
}
关于javascript - Angular js : Controller Function : variables : 'var' or controller propeties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33774917/