我想做一个小的应用程序。我做到了,但我的if
声明无效。如果有人能告诉我什么是错的,我将不胜感激。
该应用程序向用户显示一个文本框,可以在其中列出以逗号分隔的项目。如果文本框中的项目数小于或等于3(例如,1,2或3),则应在文本框下面显示一条消息,说“" Enjoy!"”。如果项目数大于3(4,5及以上),则消息“太多了!”#34;。为了实现这种行为,我使用了split方法。如果文本框为空并且用户单击"检查是否太多"按钮,消息"请先输入数据"应该出现。
这是我的代码:
(function () {
'use strict';
var app = angular.module('LunchCheck', []);
app.controller('LunchCheckController', LunchCheckController);
LunchCheckController.$inject = ['$scope'];
function LunchCheckController($scope) {
$scope.name;
$scope.message;
$scope.displayNumeric = function () {
console.log($scope.name);
console.log($scope.name.length);
var lungimea = $scope.name.length;
console.log(lungimea);
if (lungimea == null) {
$scope.message = "Please enter data first";
}
else {
$scope.name = $scope.name.split(" ");
console.log($scope.name);
if ($scope.name.length = 3) {
$scope.message = "Enjoy!";
}
else {
$scope.message = "Too much!";
};
};
};
};
})();

<!doctype html>
<html ng-app="LunchCheck">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="LunchCheckController">
<form>
<input type="text" ng-model="name" placeholder="Check it!" />
<button ng-click="displayNumeric()">Check If Too Much</button>
</form>
{{message}}
</div>
</body>
</html>
&#13;
答案 0 :(得分:0)
您缺少将逗号分隔的项目与字符串分开的部分。使用$scope.name.length
将仅返回输入的字符数。
var lungimea = $scope.name.length;
console.log(lungimea);
if (lungimea == null)
{
$scope.message = "Please enter data first";
}
else
{
$items = $scope.name.split(",");
$scope.message = $items.length <= 3? 'Enjoy!' : 'Too much!';
};
将为您提供以逗号分隔的项目数量。
还尝试将项目存储在不同的变量中,而不是替换$scope.name
一个(请记住,您有一个ng-model
听取该变量)
答案 1 :(得分:0)
从上面给出的示例中,我假设您需要以空格分隔的单词,您可以使用下面的示例实现此行为,其中我引入了一个局部变量以避免更新绑定到输入的范围变量。 / p>
(function () {
'use strict';
var app = angular.module('LunchCheck', []);
app.controller('LunchCheckController', LunchCheckController);
LunchCheckController.$inject = ['$scope'];
function LunchCheckController($scope) {
$scope.name;
$scope.message;
$scope.displayNumeric = function () {
if (!$scope.name) {
$scope.message = "Please enter data first";
}
else {
let nameSplit = $scope.name.split(" ");
if (nameSplit.length <= 3) {
$scope.message = "Enjoy!";
}
else {
$scope.message = "Too much!";
};
};
};
};
})();
&#13;
<!doctype html>
<html ng-app="LunchCheck">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="LunchCheckController">
<form>
<input type="text" ng-model="name" placeholder="Check it!" />
<button ng-click="displayNumeric()">Check If Too Much</button>
</form>
{{message}}
</div>
</body>
</html>
&#13;
我希望这会有所帮助。