What is the best way to detect an empty string in AngularJS?

When working with a form, I needed to ensure that a string is not empty. If the string is indeed empty, I wanted to set a default value. Otherwise, I wanted to pass the actual value.
Below is the code snippet from the controller:

$scope.addElem = function () {
    $scope.lista2.push({
        com: null ? com = 'VUOTO' : com = $scope.newItem.com,
        gruppo: null ? gruppo = 'VUOTO' : gruppo = $scope.newItem.gruppo
    });
};  

And here is the corresponding HTML code (Bootstrap is also used):

<form class="form-inline" name="input">
    <input type="text" class="form-control col-5" ng-model="newItem.com" placeholder="Nome del comico" ng-keypress="$event.keyCode == 13 && addElem()" />
    <input type="text" class="form-control col-5" ng-model="newItem.gruppo" placeholder="Gruppo del comico" ng-keypress="$event.keyCode == 13 && addElem()" />
    <button class="btn btn-outline-secondary btn-sm col-2" type="submit" ng-click="addElem()">Inserisci</button>
</form>

Answer №1

The way you've structured your ternary condition is incorrect. Modify it following the example below for it to function properly:

$scope.addElement = function () {
    $scope.list2.push({
        comment: $scope.newItem.comment === null ? 'EMPTY' : $scope.newItem.comment,
        group: $scope.newItem.group === null ? 'EMPTY' : $scope.newItem.group
    });
};  

Answer №2

It appears that an attempt was made to use ternary operators in order to assign values to object properties. The following code snippet will assign the value of com to $scope.newItem.com if it returns a truthy value, otherwise it will default to "VUOTO". The same logic applies to gruppo.

$scope.lista2.push({
    com: $scope.newItem.com ? $scope.newItem.com : "VUOTO",
    gruppo: $scope.newItem.gruppo ? $scope.newItem.gruppo : "VUOTO",
});

Answer №3

Is it possible to remove unnecessary characters from a data string?

$scope.addElem = function () {
  $scope.lista2.push({
    com: $scope.newItem.com.trim().length === 0 ? com = 'EMPTY' : com = 
  $scope.newItem.com,
    gruppo: $scope.newItem.gruppo.trim().length === 0 ? gruppo = 
    'EMPTY' : gruppo = $scope.newItem.gruppo
  });
};

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

The controller is not receiving the output from the factory function

When my controller receives {"$$state": {"status" :0 } } from the factory instead of the expected value, how can I extract the correct value from the factory? Below is my code in controller.js: .controller('omnipayLoginCtrl', ['$scope&apos ...

What is the best way to pass the "getjson" capability from one function to another in a seamless manner?

Currently, I am dealing with a situation where a getjson call is used to retrieve a large amount of data. However, I find myself constantly having to check if the data is null or not. Here is an example: if (data.Height == "") { $(&ap ...

what is the process for configuring a Universal link using javascript?

I have taken all the necessary steps to utilize a universal link. I created an AASA file, verified it using aasa-validator, and configured it in XCODE as required. Now, I am facing the challenge of setting up a hyperlink on my webpage that can redirect us ...

Ways to access and retrieve data from Vuex store values?

Combining vuex and vuejs 2 for the first time. I'm a beginner with vuex and I need to monitor changes in a store variable. Trying to implement the watch functionality within my vue component. This is my current code snippet: import Vue from ' ...

Combine the remaining bars by stacking the highest one on top in Highchart

Making use of stacking to display the highest value as the longest column/bar, with smaller values being merged within the highest one, can create a more visually appealing stack chart. For example, when looking at Arsenal with values of 14 and 3, ideally ...

Using JSON to create bootstrap styled link buttons

My current code is functioning well with links. However, when I try to use a bootstrap button instead of a regular button, the button appears in the table but no longer directs to the link. var button = "<button class='btn btn-inf ...

Is SWR failing to provide outdated data?

My understanding was that SWR should display the cached data upon page load before refreshing with new information from the API. However, in my Next.js app with a simple API timeout, the "loading" message appears every time due to the 5-second delay I adde ...

Issues have been reported regarding the paramMap item consistently returning null when working with Angular 8 routing

I am encountering an issue with Angular 8 where I am trying to fetch some parameters or data from the route but consistently getting empty values. The component resides within a lazy-loaded module called 'message'. app-routing.module.ts: ... { ...

Determine if the input text field contains any text and store it in a variable using jQuery

I'm working on a form that includes radiobuttons and textfields. To keep track of the number of checked radiobuttons, I use this code: var $answeredRadiobuttons = $questions.find("input:radio:checked").length; But how do I store the number of textf ...

Troubleshooting: JavaScript code not functioning properly with variable input instead of fixed value

I have encountered an issue with a JS function that I'm using. The function is shown below: // A simple array where we keep track of things that are filed. filed = []; function fileIt(thing) { // Dynamically call the file method of whatever ' ...

What other options are available besides componentDidUpdate for retrieving the chosen date from a date picker and including it in an API request?

Currently, I am utilizing react-dates to implement a datepicker feature. Whenever the user modifies the date, it updates a prop that is then sent to the backend as a parameter in a query to fetch specific results for that particular day from the database. ...

Retain the jQuery dropdown menu in an open state while navigating to a different webpage on the

I am encountering an issue with a drop-down menu on my website. Whenever I click on a submenu link, the new page opens but the menu automatically closes. However, I want the active menu to remain open even on the new page. To solve this problem, I believe ...

Scale transformation - I am aiming for it to exceed the limits, yet it remains contained within

Currently, I am working on enhancing my carousel by implementing a zoom effect when hovering over the images. However, I have encountered an issue where the image gets hidden within the div container and doesn't overflow as expected. I tried adjusting ...

Node JS does not receive a response from JQuery Ajax

I have developed a form on the client side which includes: <html> <body> <script> $(document).ready(function() { $.ajax({ url: "Search.html", type: "POST", dataType : "json", s ...

jQuery not being applied to dynamically added dropdown element

I am currently utilizing bootstrap and jquery within my react project. I have a button that, when clicked, should transform into a dropdown field. The dropdown functions properly when placed statically, but the functionality is lost once it is dynamically ...

Value of the object is currently not defined

Having difficulty determining values in a manner that allows for later accessibility. When defining Search first, Search.commands[3] becomes undefined. On the other hand, defining commandList first results in commandList.commands[0] being undefined. Is t ...

Chrome's XPath attribute selection is not functioning properly

After running a small test with expect.js, here are the results: describe('xpath', function () { it('locates attribute nodes', function () { $(document.body).append('<string fooBar="bar"><data id="xyz">< ...

How can I obtain the true client IP address using Nginx?

I have a straightforward express app that has been containerized using Docker. You can find the repository here. In this setup, I utilized nginx as a reverse proxy. When accessing http://45.33.97.232:3000, it displays the actual server IP. However, if I v ...

Unable to navigate through select2 dropdown if fixed div is present

I am facing an issue with select2 in my fixed div popup that acts like a modal. The problem is that when the select2 dropdown is open, I am unable to scroll the div until I close the dropdown. This becomes problematic on smartphones because the keyboard e ...

NextJS - The server attempted to execute the find() function, which is only available on the client side

When attempting to utilize the .find method within the server component, I encounter an error. export async function TransactionList() { const transactions = await fetch('/transactions'); return ( <ul> {transactions.m ...