$scope.cal = function (){
var totalItems = stringSplit($scope.eatables);
$scope.value = totalItems;
if(totalItems == 0){
$scope.message = "Please enter something";
}else if(totalItems <= 3){
$scope.message = "Enjoy!";
}else{
$scope.message = "TOO MUCH!";
}
};
function stringSplit(string){
var array = string.split(" ");
var x = array.length;
return x;
};
我在ng-click
上调用此函数,但是当输入框为空时,它仍然给出值1.为什么会这样?
答案 0 :(得分:0)
这个怎么样?
function stringSplit(string){
var array = string.split(" ");
var x = array.length;
return (array[i] === "" || array[i] === null || array[i] === undefined) ? 0 : x; //Check whether first element is empty
};
答案 1 :(得分:0)
所以要在拆分它之前解决这个问题,你可以检查是否存在某个值,然后只拆分
像这样改变你的功能
function stringSplit(string){
var x
if(string){
var array = string.split(" ");
x = array.length;
alert(string)
alert(x)
return x;
}else {
x =0
return x
}
};
这里是工作代码笔样本 http://codepen.io/vkvicky-vasudev/pen/XjkZBN