Update JSON data in ng-blur event using AngularJS

Could you offer some guidance on how to push the content from a text box into JSON when I click outside of the box? Below is the code for my text box:

<input type="text" name="treatmentCost" class="form-control" ng-model="addTemplate" />

And here is the JSON structure I am working with:

$scope.existingTemp = [{"name": "template1"},{"name": "template2"},{"name": "template3"},{"name": "template4"},{"name": "template5"}];

Any suggestions or ideas are greatly appreciated. Thank you in advance.

Answer №1

If you want to achieve this, you can utilize the ngBlur directive.

Here is an example of how it can be implemented:

<input type="text" ng-model="addTemplate" ng-blur="addValueToJson(addTemplate)"/>

In your controller, you would have the following code:

$scope.addValueToJson = function(value){
   var newObj = {name: value};
   $scope.existingTemp.push(newObj);
};

You can see a working demo in this JSFiddle.

I hope this information proves useful to you.

Answer №2

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8d9d6dfcdd4d9ca96d2cbf889968b">[email protected]</a>" src="https://code.angularjs.org/1.3.10/angular.js" data-semver="1.3.10"></script>
  <script>
    var app = angular.module('plunker', []);

    app.controller('MainCtrl', function($scope) {
      $scope.data=[];
      $scope.fill=function(){
        $scope.data.push("name:"+$scope.addTemplate);
        console.log(JSON.parse(JSON.stringify($scope.data)));
      }
    });
  </script>

</head>

<body ng-controller="MainCtrl">
 <input type="text" name="treatmentCost" class="form-control" ng-model="addTemplate" ng-blur="fill()"/>
</body>
</html>

Check out this Plunker: http://plnkr.co/edit/rR0Sl0ZE7xTrZmIonVAI?p=preview

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

Utilizing Angular 2 for dynamic CSS binding: manipulating style.width and style.height properties

I am experiencing some unusual rendering issues when using plain HTML5 canvas and CSS binding with A2. Can anyone please explain the difference between the following code snippets: <canvas height="400" width="1200" #background> </canvas> AND ...

What's the deal with peculiar symbols and PHP's Json_Encode?

I've encountered an issue while using JSON_ENCODE in PHP to display data. When it comes across the word: Æther, it prints out as \u00c6ther. Does anyone have a solution for making the JSON output show that character correctly, or will I need to ...

Guidelines for implementing a logout feature in Django using templates

Here is my views.py file: from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt import os # Create your views here. @csrf_exempt def index(request): if('loggedIn' in request.session): id = request. ...

Using React - What is the best way to invoke a function from within a different function?

Imagine this scenario: class Navigation extends React.Component { primaryFun() { console.log('funn') } secondaryFun() { this.primaryFun(); } } I assumed that calling primaryFun within secondaryFun would work as expected, but instead I rec ...

Highlight the phrase "figure x" within the paragraph to emphasize its importance

I want to emphasize figure 1, figure2, ...all the way up to figure 111. I am limited to making changes in HTML and CSS only, without using JavaScript or jQuery. Is there a different method than just inserting <strong> in the HTML? In CSS, we have : ...

Why are two vertical scrolls appearing on the screen simultaneously?

I utilized this method to hide the body scrollbar initially and then display it upon clicking a link: $('body').css('overflow', 'hidden'); $('#site').click(function(e) { $('#wrapper').remove(); $(& ...

When multiple checkboxes are selected, corresponding form fields should dynamically appear based on the checkboxes selected. I attempted to achieve this functionality using the select option method

Require checkboxes instead of a selection option and have multiple checkbox options. Depending on the checked checkboxes, different form fields should appear. A submit button is needed. I have included some CSS code, but a more detailed CSS code is requir ...

I'm using Bootstrap (version 5.3) and when I tried to replicate the features from the examples, I noticed that the background isn't being copied over

I encountered an issue today while working on a website using bootstrap. I was copying features from examples in the bootstrap section, but when I pasted the code into my coding platform, the background appeared transparent and did not display as expected. ...

Discover every user receiving a database object instead of individual records with mLab

While using my express application with the mLab database, I encountered an issue. When trying to find only one record, everything works fine. However, when attempting to retrieve a list of users from the database, I receive the following response. Query ...

Enhance the dimensions of images on Tumblr

Is there a way to customize the width of a photo in HTML? I am having trouble changing the size of a photo set on Tumblr to be larger. I have tried researching it, but I don't understand where to place maxwidth:600px or if this is even the correct app ...

Add the information to the current JSON file

I'm currently working with an existing JSON file and attempting to add a string into it. However, whenever I write to the JSON file, the new line characters disappear and the formatting gets altered. Check out the code snippet below: #!/usr/bin/pyth ...

Using Selenium in JavaScript to upload an image is a straightforward process

I am trying to automate the process of uploading a picture using Selenium with the following script: driver.findElement(By.id(`avatar-upload`)).sendKeys(`/home/user/Desktop/smg935-0hero-0930.jpeg`) But I keep receiving this error: ElementNotInteractable ...

Utilize the pipe function to generate a personalized component

I have incorporated a custom pipe in my Angular 2 application to parse and make URLs clickable within messages displayed using an ngFor loop. If the URL links to a YouTube video, I also convert it into embed code. To optimize performance, I am looking to ...

Converting Blob to Base64 using javascript

I've managed to successfully convert my base64 (DATA_URI) image into a blob, but I'm facing issues with reverting it back. Here's what my base64 to blob code looks like for better understanding. Check out this link. b64toBlob(b64Data, cont ...

Browserify Rails encountered an error - ParseError: Error with 'import' and 'export'. These statements can only appear with 'sourceType: module'

Recently, I encountered an issue while trying to integrate an NPM package into my Rails application. The problem I'm facing can be seen in the following image: https://i.stack.imgur.com/cIOw8.png I searched this forum for similar issues but found tha ...

Experiencing difficulties with mocha and expect while using Node.js for error handling

I'm in the process of developing a straightforward login module for Node. I've decided to take a Test-Driven Development (TDD) approach, but since I'm new to it, any suggestions or recommended resources would be greatly appreciated. My issu ...

Achieve a full page layout with content and attach the footer to the bottom using flexbox in Tailwindcss and Nextjs

How can I use flex-grow to make the body section fill the screen and keep the nav fixed at the bottom? I'm having trouble figuring out which elements to apply these properties to. Can anyone provide guidance on which element should have these styles? ...

When using Mongoose paginate, there is always one missing document

I currently have a database with 6 documents and the following route: router.get('', async (req, res) => { const search = req.query.search !=null ? req.query.search : ""; const page = req.query.page !=null ? req.query.page : 1; const limit = ...

AngularJS ng-repeat is not updating when the state changes

Seeking assistance with an Angular application challenge I'm facing. I have implemented a ng-repeat in my app to display the latest messages stored in an array within a controller named "comunicacion": ng-repeat in comunicacion.html <div class=" ...

Eliminate redundant sets of comma-separated numbers from the jQuery input text value

On my webpage, there is an input with a value that looks like this: 1,7,1,4,22,58,58,1,1,4,7 <input type="text" name="hello" id="thankyouforhelping" value="" aria-invalid="false"> I have attempted mu ...