I would like to do a small aplication. I did it but my if
statement doesn't work. I will appreciate if somebody can tell me what is wrong.
The application presents the user with a textbox where they can list comma-separated items. If the number of items in the textbox is less than or equal to 3 (e.g., 1, 2, or 3), a message should show up under to the textbox saying "Enjoy!". If the number of items is greater than 3 (4, 5, and above), the message "Too much!". To implement this behavior, I used the split method. If the textbox is empty and the user clicks the "Check If Too Much" button, the message "Please enter data first" should show up.
Here is my code:
(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>
From the example you gave above, I am assuming you want space-separated words, you can achieve this behavior with the below example where I have introduced a local variable to avoid updating the scope variable which is bound to the input.
(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!";
};
};
};
};
})();
<!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>
I hope this helps.