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

Understanding the role of $element and $attrs in component controllers within AngularJS components version 1.5

Currently, I am in the process of familiarizing myself with 1.5 angular components. To kickstart my learning, I have been watching Todd Motto's videos and also referring to Angular's official documentation here. It appears that components are re ...

What is the best way to identify the property of an object that holds a specific value?

Searching through an object array in JavaScript to find a specific value and identify the property containing that value is my current task. Here's an example: Object Array: var objArray = [{ "ID": 1, "Name": "Kathy", "Position": "Progra ...

The error message encountered while using String.search("sinh(2"): "Regular expression is invalid."

Encountering an issue: var test = $("#k_w").val().search("sinh("+parseFloat(sinh_array[i])); An error message is displayed by the debugger: Uncaught SyntaxError: Invalid regular expression: /sinh(2/: Unterminated group. sinh_array[i] represents numerica ...

Understanding the concept of objects in JavaScript can be quite essential for

As I delve into a JavaScript file, I stumble upon the following lines: var myPage = new Object(); var myDocument = document.all; After some code, there is another interesting snippet: myPage.Search = myDocument.Search; myPage.Search.searchType = "Descri ...

JavaScript AJAX function is returning an undefined value rather than a boolean true or false

My AJAX call function in jQuery has a complete section with the following code: complete: function(XMLHttpRequest, textStatus) { if(textStatus == "success") { return(true); } else { return(false); } } However, when ...

Changing a string into an ArrayList of Strings using Java

There is a string that looks like this - "["222.222.222.222", "21.21.21.21"]"; // A plain string that represents a JSON array I need to extract 222.222.222.222 and 21.21.21.21 from the string and store them in an ArrayList. Your help would be greatly ap ...

Apply design to a dynamically generated JavaScript id using Stylus

Currently, I am utilizing a jquery datepicker widget, and my goal is to customize the CSS for its input field. However, it seems that the id assigned to that field is dynamically generated upon page load: <input type="text" id="dp1382434269539" style= ...

Navigating a complex web: Djikstra algorithm applied to a multigraph

Encountering an issue while implementing Dijkstra's algorithm on a multigraph. The graph consists of nodes representing stops with information and connections to other stops (edges). However, the challenge arises when there are multiple bus options be ...

Enhance the Angular KendoGrid excelExport feature with a custom column addition event

When utilizing the excelExport event in KendoGrid to modify certain column data before exporting it, is there a way to insert a new column between two existing columns? Here's the current code I'm using to manipulate dates. I would like to add a ...

What is the web address to access when removing an object from the system?

I have set up a local server to experiment with an API in Django. My model, 'Users', is filled with multiple objects and I am utilizing DefaultRouter. If I wanted to DELETE a specific object from this model, what would the URL look like? For ins ...

My JavaScript/jQuery code isn't functioning properly - is there a restriction on the number of api calls that can be made on

Below is the code I have implemented from jquery ui tabs: <script> $(function(){ // Tabs $('#tabs1').tabs(); $('#tabs2').tabs(); $('#tabs3').tabs(); //hover states on the sta ...

Error: Attempting to access the 'email' property of an undefined element during registration

I am facing an issue with my if statement. Below is the code snippet that I am currently working with: ` app.post('/register', redirectHome, async (req, res, next)=>{ try{ const email = req.body.email; let password = req.bo ...

Associating Map with Scala attributes

Why use a JSON data structure? {"query":{"count":1,"created":"2014-04-28T07:33:09Z","lang":"en-US","results":{"rate":{"id":"USDCNY","Rate":"6.2489","Date":"4/28/2014","Time":"3:30am","Ask":"6.2494","Bid":"6.2484"}}}} The specific data of interest is: ...

Utilize JavaScript or jQuery to segment HTML elements

Looking for a front-end solution to a common practice. In the past, I've stored reusable HTML elements (such as <nav>, <header>, <footer>, etc.) in a functions.php file and used PHP functions to include them on multiple pages. This ...

Continuously converting methods recursively until the array is fully processed

My current code has a method that is not very efficient and does not scale well. The object y is an array consisting of key/value pairs, each containing two properties: 1. A unique string property called name. This value is identified by the childre ...

It appears that when filtering data in Angular from Web Api calls, there is a significant amount of data cleaning required

It appears that the current website utilizes asp.net web forms calling web api, but I am looking to convert it to Angular calling Web api. One thing I have noticed is that I need to clean up the data. How should I approach this? Should I use conditional ...

The 'disabled' property is not found in the 'MatButton' type, however, it is necessary in the 'CanDisable' type

Issue found in node_modules/@angular/material/core/option/optgroup.d.ts: Line 17: Class '_MatOptgroupBase' does not correctly implement interface 'CanDisable'. The property 'disabled' is missing in type '_MatOptgroupBas ...

Is there a way to close the menu in react by clicking anywhere on the

Presently, I have a solution to close my topbar menu that involves clicking the menu icon. However, this method is not satisfactory because it only closes the menu when the icon is clicked. I am looking for a way to make the menu close when any area of th ...

Effortlessly uploading large files using axios

I am currently facing an issue and I am seeking assistance. My goal is to implement file chunk upload using axios, where each chunk is sent to the server sequentially. However, the requests are not being sent in order as expected. Below is a snippet of m ...

Can GET or POST variables be transmitted to external JavaScript?

Is it possible to pass a variable to an external JavaScript file? For instance: Suppose I have the following code: <script type="text/javascript" src="gallery.js"></script> I'm curious to know if it's feasible to pass an argument ...