How can I include a JSON object in an angularjs $scope variable?

How can I effectively inject my JSON Object into my angular $scope during the create() function?

Sample HTML:

<input type="text" class="title" placeholder="hold" ng-model="formData.text"/>
<input type="text" class="desc" placeholder="description" ng-model="formData.desc"/>

<button type="submit" class="btnCreate" ng-click="createRule();direction('front');go('/myrules')">CREATE
</button>

Controller code:

$http.get('/public/mdm/default.json').success(function (data) {

            $scope.data = data;
            console.log($scope.data);
        })

$scope.formData = {};

$scope.createRule = function () {
            Rules.create($scope.formData)
                .success(function (data) {
                    $scope.formData = {};
                    $scope.rules = data;

                    // Now, how do I properly add my JSON to this creation...
                });
        };

The issue lies in populating $scope.formData with an Object where push() cannot be used...

$scope.formData[JSONObject] = $scope.data;
is not working as expected.

I believe there must be a simpler way to accomplish this task. Any assistance or guidance on this matter would be greatly appreciated. Thank you in advance!

Answer №1

Assigning the JSONObject to $scope.formData.JSONObjectProperty should solve it.

This should work perfectly.

Answer №2

$scope.formData[JSONObject] = $scope.data; 

It seems that using JSONObject as a key for the formData object hash may not be valid.

Have you considered changing it to a more appropriate name?

$scope.formData["JSONObject"] = $scope.data 

Alternatively, you could simply merge the objects by assigning $scope.data to $scope.formData.

On a related note, there is a question on Stack Overflow regarding AngularJS factory and $http.get for JSON files: AngularJS: factory $http.get JSON file

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

What could be causing the error "memoryview: a bytes-like object is required" to appear when attempting to utilize gzip.compress on JSON data?

When I try to read a JSON file from S3, the process involves: json_file = s3_resource.Object(bucket_name='test', key='new.json' json_content = json.loads(file_content) .... gzipped_content = gzip.compress(json_content) Once the file is ...

Delete elements with identical values from array "a" and then delete the element at the same index in array "b" as the one removed from array "a"

Currently, I am facing an issue while plotting a temperature chart as I have two arrays: a, which consists of registered temperature values throughout the day. For example: a=[22.1, 23.4, 21.7,...]; and b, containing the corresponding timestamps for eac ...

Using Codeigniter to Access JSON Data after Successful AJAX Post

<label>Choose Group</label> <select id="group" name="groupName"> <option value="0">Select Group</option> <?php foreach ($userGroup as $item) { ?> <option value="<?= $item->n ...

What could be causing my data to shift after refreshing in Firefox with the F5 key?

My webpage has four tables, each containing rows with two text boxes filled with numeric values from the server. However, something peculiar occurs. When I add data to a row, let's say row 1, and then refresh the page, two values are mysteriously mov ...

Filtering in AngularJS can be done based on the comma-separated elements

I am trying to implement a filter in AngularJS for a specific JSON format value [ {"id":"1","video_title":"Sample1","tags":"2,12,13","featured":"1"}, {"id":"2","video_title":"Sample2","tags":"5,13","featured":"1"}, {"id":"2","video_title":"Sample3","ta ...

Even in the absence of the element on the page, the VueJS instance is still being invoked

I am encountering an issue where all my VueJS instances are being executed, even if the element associated with them is not present on the page. Currently, I have defined a mixin as follows: var mixin = { methods: { listEvents(parameters) { ...

What is the process of implementing session storage in an AngularJS directive?

I am trying to save values in Angular session storage within an Angular directive, but I am facing an issue where I only receive NULL. Can anyone provide assistance? app.directive('myDirective', function (httpPostFactory) { return { restrict ...

In-Place Editing Revolutionizing Content Editing

What is the most effective method for editing content while using ng-repeat? In an ideal scenario, the added birthday would be displayed as a hyperlink. When clicked, it would reveal an edit form similar to the add form, along with an update button. Chec ...

What is the process for transferring image attributes to the server via a URL?

My data transmission process only involves sending data. Below is the data I send: export const cabin = { name: '001', maxCapacity: 2, regularPrice: 250, discount: 0, image: './cabins/cabin-001.jpg', description: ...

Specialized spinning tool not in sight

Having an angular 11 application with a spinner that should be visible during data loading from the backend. However, when the fa-icon is pressed by the user, it becomes invisible while waiting for the server response. The issue arises when the spinner its ...

The ng module instantiation failed because of an error related to an unresolved dependency for $logProvider. More information can be found at http://errors.angularjs.org/undefined/$injector/unpr?p0=%24log

I have created this code snippet to enhance the $log functionality: window.fofr = window.fofr || {}; window.fofr.library = window.fofr.library || {}; window.fofr.library.logging = window.fofr.library.logging || {}; window.fofr.library.logging.errorLo ...

Tips for showing the chart title and subtitle using "vue-google-charts" library by devstark: Where to position them - top or bottom?

Utilizing the resource available at https://www.npmjs.com/package/vue-google-charts The title is not being displayed on the chart. Is there a way to show it either above or below the chart? I attempted adding "display=true" with the option "title" and fo ...

I am looking to have the first option in the dropdown menu appear as a placeholder text

In my form, I have two phone number fields - one for mobile phone and the other for home phone. I need to make only one of them mandatory. Can someone please advise me on how to accomplish this? ...

Material Design Forms in Angular: A Winning Combination

I'm currently working on developing a form using Angular Material. This form allows the user to update their personal information through input fields. I am utilizing "mat-form-field" components for this purpose. However, there are certain fields tha ...

I am struggling to grasp the concept of integrating JSON.NET with ASP.NET Core WebAPI

After completing my first ASP.NET Core Web API project, I am interested in exploring manual JSON serialization/deserialization using the JSON.NET library. The JSON.NET documentation provides a simple example of manual serialization which involves creating ...

Combine es6 imports from the identical module using an Eslint rule or plugin

Looking to consolidate my ES6 imports from a single module into one for my React project. For example: import { Title } from "@mantine/core"; import { Center } from "@mantine/core"; import { Divider } from "@mantine/core"; T ...

personalized link when uploading images in Jodit Editor

I recently integrated the Jodit Editor (react) with the Insert Image option, allowing users to upload images that are saved in the default location set by the Editor. Now I am curious about how to use a custom URL to insert an image in the editor. Here i ...

Delayed callback on blur

I am developing an AutoComplete feature in React that displays a list of suggested completions as the user types into a text box. When a suggestion is clicked, it should trigger a callback function, and the dropdown should disappear when the text box loses ...

What is an example scenario where Async Storage can be tested using Jest-expo?

To better understand the testing of Mock-async-storage for reactjs, I decided to replicate an example. If you have any suggestions on a different approach to testing, please feel free to share. I attempted to mimic a use case illustrated on this stack over ...

Resizing svg to accommodate a circle shape

As I work on my vue.js app that involves a plethora of diverse icons, I made the decision to create a small icons builder in node.js. The purpose is to standardize their usage and also "crop" each SVG so it fits perfectly within its parent container by uti ...