Calculator for Angular User Input

Looking to create a simple application, I encountered an issue with my if statement. I would greatly appreciate any help in identifying the problem. The goal of the application is to provide users with a text box where they can input comma-separated items. If the number of items entered is 3 or fewer, a message should appear below the textbox saying "Enjoy!". For more than 3 items, the message should be "Too much!". To achieve this functionality, I utilized the split method. In case the textbox is empty and the user clicks the "Check If Too Much" button, a message stating "Please enter data first" should display.

Below is the code snippet:

(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 length = $scope.name.length;
            console.log(length);
            if (length == 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>

Answer №1

Based on the example previously provided, it seems like you are looking to separate words with spaces. You can achieve this functionality using the following code snippet, which includes a local variable to prevent updating the scope variable associated with the input field.

(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>

Hopefully, this solution meets your needs.

Answer №2

Don't forget to separate the items in your string that are separated by commas. If you use $scope.name.length, it will only give you the character count of the input.

var length = $scope.name.length;
            console.log(length);
            if (length == null)
            {
                $scope.message = "Please enter data first";
            } 
            else 
            {
                $items = $scope.name.split(",");
                $scope.message = $items.length <= 3? 'Enjoy!' : 'Too much!';
            };

This will provide you with the number of items separated by commas.

Also, try saving the separated items in a new variable instead of replacing the existing $scope.name one (keep in mind there is an ng-model tied to that variable)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop span elements from being removed within a `contenteditable` container

I am facing a challenge with an editable div that contains a span element which I would like to prevent users from deleting. My development environment is Vue3. Currently, if the user presses backspace while their cursor is to the right of the span or sel ...

Phonegap's JavaScript canvas feature is experiencing issues

Recently, I came across a JavaScript bouncing ball animation that works perfectly on the Chrome browser when used on a PC. However, when I tried running it using Phonegap Eclipse Android emulator, I encountered an issue where the canvas appeared blank and ...

What is the best way to bring in the original files of a JavaScript library?

Currently I am utilizing a library called selection.js. Within my application, I am importing from node_modules with the following code: import * as Selection from '@simonwep/selection-js' However, what I am interested in doing is modifying the ...

The Angular datepicker is failing to trigger the ng-change event

I've run into a snag with the datepicker and ng-change functionality. Oddly enough, the ng-change event isn't triggering when I manually select a date by clicking on it, but it works fine when I input a date manually. Take a look at my code snip ...

Various successful functions in Ajax

I am currently using an Ajax script to fetch data from my database and insert it into multiple textboxes. Along with posting the data, I also need to perform calculations using these textboxes. However, upon running the script, I noticed that all calculat ...

Utilize data from two distinct JSON sources that are updated at varying intervals, and display the combined results in an ng-repeat

I am currently working on creating a status list that pulls data from two separate JSON sources. The main purpose of this list is to show general information from the first source, while also indicating a status color based on the number of people in the s ...

Receiving an error when attempting to utilize a value from the .env file in createSecretKey function

Currently, my code looks like this: const secretKey = crypto.createSecretKey( Buffer.from(process.env.SECRET, "hex") ); However, I am encountering the following error message: "The value of 'key.byteLength' is out of range. It must be > ...

Display list items in HTML based on the length of an array

In my backend, I have a user-defined array of cars. If the user selects 3 cars, the array will contain 3 elements. I would like to display specific details of the cars in HTML elements within a list. The array is based on JavaScript. Here is an example of ...

Retrieve object containing all identical fields except for one specific field

Looking for help with filtering a JavaScript object [ { "comparing_result": "d_sens", "event": "Require", "master_field": "type_de_donnees", "master_field_ ...

Failure to respond to dual part form by RemoveClass

Currently, I am utilizing jQuery to visually control a form. The issue arises when trying to remove classes from the first part of the form using removeClass. While this works initially, upon clicking the button to advance to the second part of the form, t ...

Determine the elapsed time in seconds between two specified moments

I am trying to implement two input fields in my HTML, one for a starting point and another for an end point. The user will enter two times like this: For example: [8:15] - [14:30] alert("XXXXX seconds") I want to calculate the number of seconds between 8 ...

A guide to displaying a countdown timer in an Angular application during the app's loading process

Displaying a loader that shows the time in seconds while loading an app is my goal. Here is the code snippet: HTML <body> <div class="app-loader"> <div class="loader-spinner"> <div class="loading-text"></div> ...

What is the best way to display data from the Nuxt.js store?

I am new to Nuxt JS and following a tutorial on the Nuxt website. I created a store in store/index.js. export const state = () => ({ mountain: [], }) export const mutations = { addMountain(state, mountain) { state.mountain.push(mountain) }, } ...

Using JS regular expressions to only select anchor (a) tags with specific attributes

When trying to select a link tag (a) with a specific data-attr, I encountered an issue. I currently use the following regex pattern: /<a.*?data-extra-url=".*?<\/a>/g. However, I noticed that this selection goes wrong when there are no line br ...

Challenges with handling callbacks in Javascript

I'm currently working on creating a user-friendly GUI using the w2ui library, but I've encountered an issue with integrating a toolbar into my main layout. The problem arises when the toolbar is added before the layout is fully constructed. Sinc ...

Using jQuery to dynamically include option groups and options in a select box

Generate option groups and options dynamically using data retrieved via AJAX. <select name="catsndogs"> <optgroup label="Cats"> <option>Tiger</option> <option>Leopard</option> <option>Ly ...

"I am sending a JSON object to a PHP script and extracting the

I have created a form with PHP like this: <?php include '../db/baza.php'; ?> <?php include 'vrh.php' ?> <div id="page"> <div id="pageFrame"> <form action="up ...

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...

Adjusting the content of a single text box by typing in another

Is it feasible to automatically convert a Nepali date input in one textbox into an English date and display it in another textbox without any page refresh? I have a PHP function that can translate dates between Nepali and English, and I want it to execute ...

It is not possible to utilize a JavaScript function once the script has been loaded through

I am attempting to programmatically load a local JavaScript file - PapaParse library, and then utilize one of its functions: $.getScript("./Content/Scripts/papaparse.js", function () { console.log("Papaparse loaded successfully"); Papa.parse(file, ...