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

Repeatedly view the identical file on HTML

I'm currently working with the following HTML code: <input type="file" style="display: none" #file(change)="processImage($event)" /> <button type="button" class="btn" (click)="file.click()" Browse </button> When I select image1 fr ...

How can I display components using Angular CLI 5 without any visual output?

The index.html page is not displaying anything, not even the "App works" message that should appear in a basic initial project ng --version Angular CLI: 1.6.0 Node: 8.9.1 OS: darwin x64 Angular: 5.1.0 ... animations, common, compiler, compiler-cli, core, ...

The menu is loaded dynamically by Ajax from JavaScript once the page is refreshed

$('#subregionListPage').bind('pageinit', function(event){ var output = $('#subregions'); var region = getUrlVars()["reg"]; $.ajax({ url: 'http://localhost:8888/my/getsubregions.php', dat ...

Is NextJS 13 the Key to App Directory On-Demand Revalidation?

I am looking to implement on-demand revalidation with next13 and the app directory. While I have successfully used the app-directory to replace the need for getServerSideProps or getStaticProps, there is one specific page on our site that needs to be rebui ...

What could be causing my Link to malfunction in my about.js file?

I've encountered an issue where clicking the link in my app doesn't produce any result, and I'm unsure of the cause. Below is the content of my app.js file: import './App.css'; import {BrowserRouter as Router, Routes, Route} from ...

Strategies for aligning tooltips with the locations of dragged elements

One of my projects involves a simple drag element example inspired by Angular documentation. The example features a button that can be dragged around within a container and comes with a tooltip. <div class="example-boundary"> <div ...

Click on the text within a paragraph element

Is there a way to retrieve the selected text or its position within a paragraph (<p>)? I'm displaying a text sentence by sentence using a Vue.js loop of paragraphs. <p class="mreadonly text-left mark-context" v-for="line in ...

Utilizing express.js alongside the native MongoDB driver: A comprehensive guide

I'm facing difficulties when attempting a simple mongoDB query from my express app: app.js var express = require('express'); var routes = require('./routes'); var user = require('./routes/user'); var http = re ...

The canvas's document.getElementById function is unable to find any matching element,

Hello everyone, I am currently diving into the world of javascript and trying to expand my knowledge. However, I have encountered a problem that has me stumped, and I could really use some assistance. While exploring, I came across this page: http://www.w ...

What is the best way to assign dynamic values for array destruction?

Is there a way for me to avoid manually writing out six lines by implementing a loop to retrieve all six values from one line instead? console.log(array[0].name.LINE1) console.log(array[0].name.LINE2) console.log(array[0].name.LINE3) console.log(array[1].n ...

styles.css is generating an ERROR message, indicating that it is unable to read properties of null when trying to access the 'classList'

Hey there, I've been working on adding a background color change to my navbar when the scrollY exceeds 30px, and it's functioning properly. However, I'm encountering an error in the console which states that the new classList cannot be added ...

Similar to LINQ's Enumerable.First(predicate) method but with a slightly different syntax, this

When working with JavaScript, we often encounter situations where we need to find the first matching element based on certain conditions. Take for example this code snippet: function process() { var firstMatch = ['a', 'b', 'c&ap ...

Activate a function when the v-data-table in Vuetify is expanded and then collapsed

While trying to create a v-data-table, I came across some odd behavior when monitoring the expanded.sync value. The first layer's expanded.sync value seems normal, but the second layer's expanded.sync has three consecutive identical records. I w ...

Unleashing the potential of Chrome's desktop notifications

After spending the past hour, I finally found out why I am unable to make a call without a click event: window.webkitNotifications.requestPermission(); I am aware that it works with a click event, but is there any way to trigger a Chrome desktop notifica ...

Monitoring a specific property within an array of objects with AngularJS

I am facing an issue with the data in my controller $scope.data = { home: { baseValue: "1", name: "home" }, contact: { baseValue: "2", name: "contract" } // numerous ...

Employ the JSON body within the SOAP envelope when transmitting data to a WCF service

Is it feasible to incorporate a soap header for authentication into a json body? The contract has been defined as follows: [ServiceContract(Namespace = "http://tourico.com/webservices/hotelv3")] public interface IHotelMobileFlow { [OperationContract, ...

Using an array as an argument for .map() results in an error

This is quite unusual. Currently, I am passing an array containing a single object to the Render method of a React component: let content = this.state.links.map(link => { // eslint-disable-line return ( <li key={link._id}> <a href ...

The left margin is malfunctioning

As a newcomer to css, I am struggling with adding margin-left to my paragraph and <h2>, and it's not taking effect. I have a 700px div and I want to add a 10px margin-left to both <p> and <h2> in relation to the image. Despite my e ...

Three.js - Controlling Visibility of Text in troika-three-text with Clipping Planes

Has anyone successfully clipped troika-three-text for threejs using clipping planes? I'm having trouble getting it to work. import { Text } from 'troika-three-text' const minClippingPlane = new THREE.Plane(new THREE.Vector3(0, -1, 0), 1) c ...

What is the best way to send a REST API request with escaped double quotes?

I need to transmit a REST API request to my server with data that must be in the form of a string enclosed with double quotes: data=mycontent curl -X POST "$SERVER_ENDPOINT" \ -H 'Authorization: Bearer '"$SERVER_TOKEN&qu ...