Implementing Angular $resource to prepopulate a form with data

My goal is to enable CRUD operations so that when a user selects a specific item to edit, the form will automatically populate with the corresponding values for editing.

Below is an excerpt of code from the 'storeView.html' file:

<tr data-ng-repeat="store in stores | filter:search | orderBy:'name'">


                <td>
                    {{ store.name }}
                </td>

                <td class="icons-width">
                    <a href="#/Store/edit/{{store._id}}" id="edit"  data-toggle="tooltip">
                        <i class="fa fa-pencil fa-fw colorInfo" ></i>

                    </a>

                    <a ng-click="deleteStore(store._id)"  id="delete"  data-toggle="tooltip">
                    <i class="icon-trash"></i>
                    </a>

                </td>

            </tr>

When a user clicks on edit for a particular store, they will be directed to another view ('storeformView.html') containing a form pre-populated with the desired values for editing. The contents of this file are as follows:

form class="form-horizontal" name="store_form" novalidate ng-submit='AddStore()'>
                <div class="modal-header">
                    <h3>Create/Edit Store</h3>
                </div>

                <div class="modal-body">
                    <div class="form-group">
                        <label for="store_Name" class="col-lg-4 form-label">Name:</label>
                        <div class="col-lg-7">
                            <input type="text" class="form-control" ng-model="store.name" id="store_Name" name="store_Name" placeholder="Store Name" required/>
                            <div class="error" ng-show="store_form.store_Name.$dirty && store_form.store_Name.$invalid">
                                <small class="error errorFields" ng-show="store_form.store_Name.$error.required">
                                    Store Name is required.
                                </small>

                            </div>

                        </div>
                    </div>

                    <div class="form-group">
                        <label for="store_AddressLine1" class="col-lg-4 form-label">Address Line 1:</label>
                        <div class="col-lg-7">
                            <input type="text" class="form-control" ng-model="store.address1" id="store_AddressLine1" name="store_AddressLine1" placeholder="Address Line 1" required/>
                            <div class="error" ng-show="store_form.store_AddressLine1.$dirty && store_form.store_AddressLine1.$invalid">
                                <small class="error errorFields" ng-show="store_form.store_AddressLine1.$error.required">
                                    Address is required.
                                </small>

                            </div>
                        </div>
                    </div>>



                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary" ng-disabled="store_form.$invalid">
                        <i class="icon-ok-sign icon-white"></i> Save
                    </button>
                <a class="btn btn-default" href="#/Stores">
                    <i class="icon-remove-circle" ></i>
                    Cancel
                </a>

            </div>

        </form>

In addition, the 'storeFactory.js' file contains the factory method:

app.factory('Store', function ($resource) {
    return {
        getAllStores   :  $resource("/store/list" ,{},{ TypeGetStores:{method: 'get', isArray:true}}),
        getStore       :  $resource("/store/:id" ,{id : @id},{ TypeGetStore:{method: 'get'}}),

    };
});

Lastly, in the 'app.js' file, the application module 'myApp' is defined along with route configuration for various views.

var app = angular.module('myApp', ['ngCookies','ngResource', 'ngRoute']);

app.config(function ($routeProvider) {
    $routeProvider

        .when('/Stores',
            {

                templateUrl: '/app/partials/StoresListView.html'
            })

        .when('/Store/edit/:storeId',
            {

                templateUrl: '/app/partials/StoreFormView.html'
            })



        .otherwise({ redirectTo: '/Login' });
});

Answer №1

To retrieve information about your store, utilize the resolve parameter within the routeProvider configuration:

.when('/Store/edit/:storeId',
    {
    templateUrl: '/app/partials/StoresListView.html',
    resolve: {app: function($scope, Store, $routeParams) {
        $scope.store = Store.getStore({id:$routeParams.id})
        }
    }

If everything is set up correctly and the factory functions as intended (returning the store data), you will have access to $scope.store in your controller, allowing for seamless two-way binding with your form input fields.

Important: The page will only be visible after the resolve process has been completed entirely.

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

Protractor: the art of inheriting classes

I am working with a complex hierarchy of inheriting classes: The first class inherits ElementArrayFinder, and the second class inherits the first class. Here is my code: 1st class: var util = require('util'); var ElementArrayFinder = require( ...

Personalized Pagination for Data Tables

I have a client who needs a customized pagination view for DataTable. I want the pagination to look exactly like the image provided. https://i.sstatic.net/FFzkM.png To achieve this, I made modifications to the datables.js code. DataTable.js: $.extend(e ...

Using Sweet Alert to enhance the user confirmation experience on your website

I need to replace the standard confirm dialog with a customized one using Sweet Alert. The JavaScript function I want to use is located in the MasterPage. function checkDelete() { swal({ title: "Are you sure?", text: "You will not be able to r ...

Different approach in Vuejs for selecting target/currentTarget in a list

I have my current configuration set up as depicted below: [{ name: "test", tags: ["aa","bb","v"] }, ...] <div class="item" v-for="item in sdList" :data-id="item.id"> <span @click="deleteTag(item, $event)" v-for="tag in item.tags ...

In Firefox, the HTML label fails to activate the corresponding input field when the mouse is moved while clicking

If you click on the label in the example below, it will change the state of the input. document.querySelector("label").addEventListener("click", function() { console.log("clicked label"); }); label { -webkit-user-select: none; -moz-user-select: no ...

The v-bind value remains static even as the data in Vue.js updates

I created a function called changeActive that is supposed to update the value of an active boolean. Interestingly, after checking the console log, I observed that the active value changes but for some reason, the updated value is not being passed in the ...

Is it feasible to open and view a STEP file using a three.js file?

Is it possible to read STEP files in three.js for generating 3D PCB components? While the file format is different, STEP files also contain 3D component information. Are there any alternative methods for reading STEP files in three.js? Any suggestions? ...

Bidirectional binding in Angular 2 Custom Directive

I've been working on a custom directive that automatically selects all options when the user chooses "All" from a dropdown. While I was able to get my custom directive to select all options, it doesn't update the model on the consuming component. ...

A different approach to fixing the error "Uncaught (in promise) TypeError: fs.writeFile is not a function" in TensorFlow.js when running on Chrome

I've been attempting to export a variable in the TensorFlow posenet model while it's running in the Chrome browser using the code snippet below. After going through various discussions, I discovered that exporting a variable with fswritefile in t ...

Transform a button into an AngularJS directive

Is there a way to create a custom directive in HTML to represent a button? For example: <buy-button></buy-button> Here is the code that I would like to change: <md-button class="md-cornered" ng-disabled="0>=gains" ...

Failed to convert the value "hello" to an ObjectId (string type) for the _id path in the product model

i am currently using node, express, and mongoose with a local mongodb database. all of my routes are functioning correctly except for the last one /hello, which is giving me this error: { "stringValue": "\"hello\"&qu ...

Increasing a variable in MongoDB using Meteor.js based on the value of a variable in a separate document

I am facing an issue similar to this: I am struggling to modify multiple documents simultaneously. click: function() { var power = Meteor.user().power; var mult = Meteor.user().mult; Meteor.users.update({ _id: this.use ...

Hidden IFrame for Jquery File Upload

I was looking for a quick guide on setting up an AJAX-style file upload using a hidden iframe. Below is the section of HTML code related to the form: <div id = "file" class = "info"> <form id="file_upload_form" method="post" enctype=" ...

Encountering an error when trying to destructure a property of null

The concept of destructuring is fascinating, but I have been facing some challenges when trying to destructure nested objects. Consider the following code snippet: const { credit: { amount }, } = userProfile This can be risky because if the &ap ...

Iterate through an HTML table and transfer matching items along with their corresponding calculated amounts to a separate table

<html> <body> <div> <table border="1" id="topTable"> <thead> <th>Item</th> <th>Sold</th> </thead> <tbody id="topTableBody"> <tr> ...

Is it possible to determine the location of the "phantom image" while moving an object?

Is there a method to retrieve the location of the ghost image when an element is dragged? This is how the scenario is set up: <div id="test" v-on:dragstart="dragStart" v-on:drag="dragging" draggable="true" v-on:drop="drop" v-on:dragover="allowDrop"> ...

Using Angular 4 to pass a specific array element from the parent component to the child component and showcasing its value in the child's HTML

I am currently working on an Angular 4 application and in need of passing an array called NpvResults from the parent component to a child component. The goal is to access this array within the child component and display its value to the client of the chil ...

Ways to select a service in AngularJS depending on a specific parameter

In my code, I have a set of functions in two different services that are being used across multiple controllers. However, at any given point, I only use one service out of the two. Currently, I am manually changing the service name in all instances whenev ...

Executing a callback two times within a single NodeJS function

I developed a function to retrieve values from Firebase. The issue I encountered was that the variables containing the result of the Firebase query were only accessible within the Firebase operation. In order to access these variables outside the function, ...

Using this functionality on a ReactJS Functional Component

Hey everyone, I'm fairly new to using React and I'm currently trying to wrap my head around some concepts. After doing some research online, I stumbled upon a situation where I am unsure if I can achieve what I need. I have a functional componen ...