根据需要在控制器中设置方法

setting a method in the controller based on requirement

本文关键字:设置 方法 控制器      更新时间:2024-07-04

我正在处理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,要么不是有效的数值。

使用typeofangular.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;
  };
});