Converting a Javascript object to JSON format only once using AngularJS

Is it possible to convert a JavaScript object to JSON using angular.toJson only once in my code? Here is an example:

$scope.task.tags = [{"id":22,"tag":"printer","created_at":"2016-03-15" }];

$scope.create = function(task) {
   tmp.tags = angular.toJson(task.tags);
   TaskService.create(tmp);
});

In the HTML file:

<input type="text" ng-model="task.tags">
<button class="btn btn-success" ng-click="create(task)">save</button>

However, when clicking on the button multiple times, it displays {{task.tags}} differently each time:

1st result:

[{"id":22,"tag":"printer","created_at":"2016-03-15"}]

2nd result:

"[{\"id\":22,\"tag\":\"printer\",\"created_at\":\"2016-03-15\"}]"

3rd result:

[{\\\"id\\\":22,\\\"tag\\\":\\\"printer\\\",\\\"created_at\\\":\\\"2016-03-15 09:59:23\\\"}]\""

Answer №1

Consider implementing the Angular JSON filter along with the angular.isObject method:

$scope.create = function(task) {
    var taskTagsCopy = angular.copy(task.tags);

    tmp.tags = angular.isObject(taskTagsCopy) ?  $filter('json')(taskTagsCopy) : taskTagsCopy;
    TaskService.create(tmp);
});

An example demonstrating this can be found on JSFiddle. The conversion of the object occurs only once as shown in the console.

UPDATE

To prevent changes to task.tags, a angular.copy has been added.

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

"Enhancing the speed of the JavaScript translate function when triggered by a scroll

I am facing an issue with setting transform: translateY(); based on the scroll event value. Essentially, when the scroll event is triggered, #moveme disappears. For a live demonstration, please check out this fiddle: https://jsfiddle.net/bo6e0wet/1/ Bel ...

Sending both File and Json data to a web API using HttpClient

I am having trouble sending file and JSON data from HttpClient to a web API server. I can access the JSON in the server as a JSON variable, but not through the payload. public class RegulationFilesController : BaseApiController { public void ...

Emphasize the search term "angular 2"

A messenger showcases the search results according to the input provided by the user. The objective is to emphasize the searched term while displaying the outcome. The code snippets below illustrate the HTML and component utilized for this purpose. Compon ...

Angular2's change detection mechanism does not behave as anticipated after receiving a message from a Worker

Within my angular2 application, I encountered a rather intriguing scenario which I will simplify here. This is AppComponnet export class AppComponent { tabs: any = []; viewModes = [ { label: "List View"}, { label: "Tree View" }, ...

Trouble with JavaScript confirm's OK button functionality in Internet Explorer 11

Having trouble with the OK button functionality on a JavaScript confirm popup in IE11. For one user, clicking OK doesn't work - nothing happens. It works for most other users though. Normally, clicking OK should close the popup and trigger the event h ...

Outputting HTML using JavaScript following an AJAX request

Let's consider a scenario where I have 3 PHP pages: Page1 is the main page that the user is currently viewing. Page2 is embedded within Page1. It contains a list of items with a delete button next to each item. Page3 is a parsing file where I send i ...

What is preventing me from accessing React state within Tracker.Autorun?

I'm feeling lost on this one. I have implemented a Tracker.autorun function to monitor when my Mongo subscription is ready for querying (following the advice given in this previous Meteor subscribe callback). It seems to be working fine as it triggers ...

What is the best way to generate a static header in nextJS?

I am looking to create a static navbar without needing client-side fetching. Currently, I am using Apollo GraphQL and my _app.js file is set up like this: import React from 'react'; import Head from 'next/head'; import { ApolloProvider ...

Returning MVC3 JSON data for editing purposes

After writing some JavaScript code to send data to my controller, I am facing an issue: JavaScript: <script type="text/javascript> $(document).ready(function () { $("#newGrade").click(function () { var newGradeNa ...

Retrieving and handling outcomes from numerous queries using jQuery's AJAX feature

Currently, I am working on making multiple ajax calls to retrieve data in json format. However, I am wondering how I can execute several queries and get the results stored in separate variables or arrays. Can someone guide me on how to structure the querie ...

Retrieving the name of the final object in a ListView

While working on parsing this JSON data: { "technology" : [ { "title" : "Android", "images" : [ { "name" : "Android - I" }, { "name" : "Android - II" }, { "name" : "Android - III" } ] } ] } I have successfully parsed the technology and images JSON Arra ...

Exploring the ng-repeat function with a Jasmine test case to determine the total sum

Can someone assist me in creating a test case for a function that calculates the total cost of items in a shopping cart? Here is my HTML code: <table> <tr ng-repeat="x in countrynames"> <td>{{x.Goods} ...

Sending requests through RoR and receiving JSON responses - what's next?

Hey there! So I'm diving into the world of Ruby on Rails and I've managed to create a form that sends data to an external widget which then returns JSON. Here's what my form looks like: <%= form_for :email, :url => 'http://XXX.X ...

Can you explain the function of a digest attribute?

As a beginner in the world of NextJS, I am currently working on getting my first project ready for production. However, I encountered the following error: Application error: a client-side exception has occurred (see the browser console for more information ...

What is the most efficient way to halt the pipe if the value of an HTML input element remains unchanged using RxJS?

I'm currently incorporating RxJS into my Angular 9 project. My goal is to bind a keyup event to an input field and trigger an HTTP request whenever the user types a new value. Here's the code snippet I have: fromEvent(this.inputBox.nativeElemen ...

Combining Data in React Arrays

I have an array with different group types and I need to merge the results if the grouptype is the same. const locationss = [ { grouptype: "Name1", id: "1", servicetype: [ { name: "Morning", price: "5& ...

Select list does not get updated on ajax in IE9 when using angularjs $scope.$apply()

I am facing an issue while trying to update my select list with a new set of items retrieved from an ajax call. I have successfully updated the model with the new list and called $scope.$apply(), which works well in Firefox but not in IE. Could this be due ...

What is the process of transferring JavaScript code to an HTML file using webpack?

I am looking to display an HTML file with embedded CSS, fonts, and JS (not linked but the content is inside). I have the CSS and fonts sorted out, but I am struggling to find a solution for the JavaScript. My project is based on Node.js. ...

Is there a way to prevent SignalR from disconnecting when the settings window is moved?

I am currently developing a webpage that utilizes SignalR events to trigger ajax requests to our servers. These requests return a URL with a custom URI scheme that, when accessed, opens up a specific program on the client's device without leaving the ...

Doing server side function calls from the client in NodeJs

I recently embarked on a journey to learn web development and am eager to make server-side data changes when invoking client functions. Take a look at my sample server setup: const fs = require('fs'); const path = require('path'); con ...