根据需要在控制器中设置方法
setting a method in the controller based on requirement
我正在处理GalleryController
,我正在尝试添加一个名为setCurrent
的方法,该方法接受一个值并将其分配给current
。如果没有传入任何值,我需要将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;
}
};
如果您真的想检查是否传入了参数,那么唯一可靠的方法就是检查参数。长度:
this.setCurrent = function (intValue) {
if (arguments.length === 0) {
this.current = 0;
}
else {
this.current = intValue;
}
};
不过,这对我来说似乎毫无意义。如果该值为false,那么它显然要么已经为0,要么不是有效的数值。
使用typeof
或angular.isUndefined(intValue)
而非null
:-)
this.setCurrent = function (intValue) {
if (typeof intValue=='undefined') { //if(angular.isUndefined(intValue))
this.current = 0;
}
else {
this.current = intValue;
}
};
更好的方式:-)
this.setCurrent = function (intValue) {
if (typeof intValue!='undefined') { //if(!angular.isUndefined(intValue))
this.current = intValue;
}
};
您可以使用angular提供的方法检查变量是否未定义,即angular.isDefined()
/angular.isUndefined()
(首选angular方式检查)
this.setCurrent = function (intValue) {
if (angular.isDefined(intValue)) {
this.current = 0;
}
else {
this.current = intValue;
}
};
希望这能帮到你,谢谢。
您可以使用三元||运算符。。。
app.controller('GalleryController', function(){
this.current = 0;
this.setCurrent = function(pas_value) {
this.current = pas_value || 0;
};
});
我找到了另一种方法:
app.controller('GalleryController', function(){
this.current = 0;
this.setCurrent = function(intValue){
this.current = intValue || 0;
};
app.controller('GalleryController', function(){
this.current = 0;
this.setCurrent = function(checkCurrent) {
this.current = checkCurrent || 0;
};
});
相关文章:
- 数组在递归方法中设置为null
- 设置嵌套对象属性的更好方法
- Es6:能够在设置/更新/删除对象属性时调用自定义方法
- sails.js beforeCreate方法只接收required设置为true的模型属性
- 设置显示后Flash对象方法不可用:无
- 是否有任何内置方法可以更改JavaScript对象'的属性设置为某个值
- “new”关键字是在构造对象时自动设置“constructor”属性的唯一方法吗
- 如何重用ajax工厂方法来设置$scoped变量
- 在jquery中,从同一对象的属性设置输入字段和标签的正确方法是什么
- 如何在谷歌地图中设置多个信息窗口,但使用这种特定的JavaScript方法
- 根据需要在控制器中设置方法
- 如何设置方法,该方法只能删除元素的预定义值
- 模拟“类”时,为什么要在 .prototype 属性中设置方法,而不是在构造函数本身中设置方法
- 为什么在 Backbone 的设置方法中有一个 while 循环
- BackboneJS的设置方法不起作用
- OOP 设置方法无法正常工作
- 我如何在Expressjs/nodejs(设置方法)开始调用函数
- 如何处理'undefined'当我在Javascript中为对象设置方法时,从控制台中返回
- 如何在Vue.js中为一个类设置方法
- Javascript Object.defineProperty设置方法触发属性更改