gpt4 book ai didi

javascript - 根据要求在 Controller 中设置方法

转载 作者:行者123 更新时间:2023-11-30 10:06:37 25 4
gpt4 key购买 nike

我正在处理 GalleryController,我试图在其中添加一个名为 setCurrent 的方法,该方法接受一个值并将其分配给当前。如果没有传入值,我需要将current设置为0

这是我写的,但似乎不正确:

(function() {
var app = angular.module('gemStore', []);

app.controller('GalleryController', function(){
this.current = 0;

this.setCurrent = setCurrent(intValue){
if(intValue === null){

this.current = 0;
}
else {
this.current = intValue;
}
};

});

app.controller('StoreController', function(){
this.products = gems;
});

app.controller('TabController', function(){
this.tab = 1;

this.setTab = function(newValue){
this.tab = newValue;
};

this.isSet = function(tabName){
return this.tab === tabName;
};
});

我应该先按照要求设置this.current = intValue吗?

最佳答案

如果没有传入任何值,则 intValue 将是 undefined,而不是 null。所以你的函数体不起作用。

这里的另一个大问题,我只能希望是一个错字,是你有 setCurrent 而你应该有 function

我不明白你帖子末尾的问题,但这会按预期运行:

this.setCurrent = function (intValue) {
if (!intValue) {
this.current = 0;
}
else {
this.current = intValue;
}
};

如果您真的想检查参数是否传入,那么唯一可靠的方法是检查 arguments.length:

this.setCurrent = function (intValue) {
if (arguments.length === 0) {
this.current = 0;
}
else {
this.current = intValue;
}
};

虽然这对我来说似乎毫无意义。如果该值为假值,那么它显然已经为 0 或者不是有效的数值。

关于javascript - 根据要求在 Controller 中设置方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28790904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com