angular cleaned user input

I am facing some issues with ng-model and input element. Can you please check out this plunker:

http://plnkr.co/edit/PJCv1AsPns1cxuSPTZiU

My concern is that when I make changes to the input value by adding extra white spaces at the beginning and end, for example:

    some text    

and then click on save, the white spaces get trimmed (which is fine) from inputValue. However, if I edit it again, the "previous" white spaces reappear in the input. How can I prevent this? I attempted to achieve this using

angular.element($('#trimInput')).val($scope.inputValue);

and while it works, I am not entirely satisfied with this solution.

angular.module('app', [])
  .controller('trim', ['$scope', function($scope) {
    
    $scope.inputValue = "some text";  
    $scope.editMode = false;
    
    $scope.edit = function() {
      $scope.editMode = true;  
    };
    
    $scope.save = function() {
      $scope.editMode = false;  
      //angular.element($('#trimInput')).val($scope.inputValue);
      console.log($scope.inputValue);
      console.log($scope.inputValue.length);
    };
    
  }])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app">
  <div ng-controller="trim">
    <div ng-show="!editMode">
      [{{inputValue}}]
      <button ng-click="edit()">edit</button>
    </div>
    <div ng-show="editMode">
      <input id="trimInput" type="text" ng-model="inputValue" />
      <button ng-click="save()">save</button>
    </div>
  </div>
</body>

Answer №1

By default in Angular, the ng-trim directive is set to true, which means it will automatically trim the value in the scope. However, the value will not update on input, resulting in extra input. You will need to manually assign the trimmed value.

$document[0].getElementById("trimInput").value = $scope.inputValue;

To achieve this, you must inject $document into your application. This will automatically assign the trimmed value to the input when you save.

Check out the DEMO

Answer №2

Employ the following code snippet to extract value from an element with id 'trimInput':

var temp=document.getElementById('trimInput');
console.log(temp.value);
$scope.inputValue=temp.value  

For more information on why an Angular JS filter may be removing spaces, visit this thread on Stack Overflow.

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

Exploring Recursive Methods in JavaScript with Function Declarations

Recursion with function expressions raises many questions. There are two approaches to accomplishing this: one involves using a named function expression, while the other employs the arguments.callee method. However, it's important to note that the us ...

Create a d3 map specifically for a selected region based on the provided latitude and longitude coordinates

I am currently working on developing a d3 map inspired by the codepen created by Andy Barefoot: https://codepen.io/nb123456/pen/zLdqvM?editors=0010. My goal is to adjust the initiateZoom() function in a way that setting specific lat/lon coordinates for a b ...

What is the best method for choosing an Edit button that does not have any text within an ng-repeat component?

Within my Form builder, I am able to select a field type using ng-repeat and it automatically appears in the canvas. My goal is to click the Edit button of that specific element on the canvas. Whenever the edit button is clicked, additional fields are disp ...

Determining the value of an element by examining the clicked element

My goal is to determine the remaining balance in my cart based on the selected item. Let's say I have 3 items in my cart, and I choose one that costs $100. Previously, I stated that I had a total of $300. In my HTML code, there are elements with IDs ...

Issues with anchor tag click event in Firefox browser not functioning as expected

I have encountered an issue while trying to create an anchor tag in a TypeScript file. When clicking on this button, the anchor tag should be created. This functionality is working correctly in Chrome and IE, however, it seems to be not working in Firefo ...

Jquery Ajax failing to retrieve a response

Here's the jQuery script I am using to fetch data from my server: $(".login_button").click(function () { var username = $(".username").val(); var userkey = $(".userkey").val(); $.ajax({ type: "GET", url: "http://192.168.0. ...

"Upon initial activation, the CSS animation will loop twice before coming to a stop

Is there a way to create a navigation bar that starts off transparent at the top of the page and then becomes opaque as you scroll down? I have tried implementing an animation for this effect, but it seems like the animation triggers twice when it should o ...

Could there be a more efficient method to enable support for all video formats?

I have a case statement in my video validation function that checks for specific file extensions of video formats. However, I am wondering if there is a shorter way to write the code in order to allow all video formats instead of creating a long list of al ...

Error encountered: Unable to find the specified file for the multi-file upload operation

Although this question has been asked before, I am completely puzzled by my inability to make this work. My goal is to upload multiple images to my server using the code snippet below: var formidable = require('formidable'); var fs = require(&ap ...

Struggling with implementing React routing in version 4.0

Struggling to route multiple pages using BrowserRouter in Reactv4. Many online guides are outdated and not working with the latest version. Here is my setup: Index.js: import React from 'react'; import ReactDOM from 'react-dom'; impo ...

Angular POST request not transmitting parameters to SpringBoot API

In my current code, I am sending an object to the API through the following method: validateLogin(user:User):Observable<string>{ console.log(JSON.stringify(user)); return this.http.post<string>(`http://localhost:8080/login/login`, use ...

Choose multiple table cells as a unit

In this scenario, I am looking to group select multiple cells within a table. The desired functionality includes being able to click on a target cell to select it, as well as the ability to achieve selection by clicking and dragging to cover multiple cells ...

Remove the bottom border from the active tab by utilizing the <div> and <a> elements

I am facing an issue with a tabbed menu on my webpage. While the menu is functioning correctly, I am struggling to remove the bottom border from the active tab. You can view all of my test code here. While I have come across solutions using <ul> an ...

Facing issues while trying to install Definitely Typed Angular through Visual Studio NuGet, encountering frequent "Duplicate Identifiers" errors

After installing AngularJS and Definitely Typed Angular from NuGet packages in Visual Studio, everything seemed to go smoothly with no errors. However, when I tried to write to a TS file, I encountered angular errors throughout the d.ts folder. Hovering ov ...

What is the process for assigning an object or array to a different object?

I'm currently developing a function that accepts a list structured like this: const payload = [ [1, 2], [1,2,3], { name: 'sandra', age: 20, email: '<a href="/cdn-cgi/l/email-protection" class="__cf ...

React Native: Unexpected Challenge in State Updates

Below is the code I am currently using: makeRemoteRequest = () => { let items = []; models.forEach(element => { //models contains an array of different models this.pushReports(element, items); }); console.log("The item ar ...

Show off a font-awesome icon overlapping another image

My task involves fetching image source from a JSON file and then displaying it on an HTML page. https://i.sstatic.net/coOaU.png I also need to overlay a Font Awesome icon on top of the image as shown below: https://i.sstatic.net/nbrLk.png https://i.sst ...

Transforming canvas into blob with the help of cropper.js

After successfully creating an application with cropper.js to crop images, I encountered a challenge. Once the image is cropped, my goal was to send it as a blob to the server for storage. Referring to the documentation of cropper.js, it suggested using c ...

Steps to verify if a value is an integer:

Lately, I've been working on a "spinner" that increments and decrements a number by 1 each time. However, I'm struggling to add validation to the program so that it only accepts integers (no decimals). I've tried looking into NaN and parseVa ...

Deactivate all checkbox items when a specific item is checked

In my checkboxlist, I have three options available: Male Female Unknown` If the user selects "Unknown", then all other selections in the checkboxlist should be disabled. In that case, nothing else can be selected. I would appreciate any assistance with ...