Exploring the concepts of angularjs $apply and $scope within the context of object manipulation

In nearly every software application, there is a necessity to modify objects.

In my scenario, I have a list of objects that can be edited on the fly with the help of Angular. However, this leads to a dilemma as exemplified by the following controller:

    app.controller('editCategoryInstant', ['$http', '$scope', '$state', '$modalInstance', 'api', '$filter', 'category', 'LRM', function ($http, $scope, $state, $modalInstance, api, $filter, category, LRM) {

    $scope.LRM = LRM;
    $scope.category = category;
    $scope.ok = function () {
        $scope.category.color = $('#color').val();
        category = $scope.category;
        if ($scope.category.icon != null) {
            $http({
                url: api.getUrl('category', category.id),
                method: "PUT",
                data: {category: $scope.category}
            }).success(function (data, status, headers, config) {

            }).error(function (data, status, headers, config) {
                var i = 0;
            });
            $modalInstance.dismiss('cancel');
        }
        else {
            alert('Select icon');
        }

    };

    $scope.cancel = function () {
        $scope.category = $scope.master;
        $modalInstance.dismiss('cancel');
    };

    $scope.clickUpload = function () {
        setTimeout(function () {
            angular.element('#fileUpload').trigger('click');
        }, 0);
    };

}]);

Let's simplify it.

I aim to modify an existing object that resembles the following:

    var category = {
    name: 'My Category',
    icon: 'fa fa-bomb',
    color: '#FFF',
    description: 'This describes the category'
};

Then I pass the category variable to the controller

The controller is connected to a modal view structured as follows:

    <div class="modal-header">
    <h3 class="modal-title" translate="STRUCTURE.CATEGORY.CREATE"></h3>
</div>
<form role="form" class="form-validation" ng-submit="ok()">
    <div class="modal-body">
        <div class="row">
            <div class="col-xs-12">
                <label class="control-label">{{'TERMS.NAME' | translate}}</label>
                <input type="text" placeholder="{{'TERMS.NAME' | translate}}" class="form-control"
                       ng-model="category.name" required>
            </div>
            <div class="col-xs-6" style="margin-top: 10px;">
                <label>{{'LIBRARY.CATEGORY.SELECTICON' | translate}}</label>
                <lb-icon-picker targetvariable="category"></lb-icon-picker>
            </div>
            <div class="col-xs-6" style="margin-top: 10px;">
                <label class="block">{{'LIBRARY.CATEGORY.SELECTCOLOR' | translate}}</label>
                <lb-color-picker targetvariable="category"></lb-color-picker>
            </div>
            <div class="col-xs-12" style="margin-top: 5px;">
                <textarea class="form-control" style="height: 150px" placeholder="{{'TERMS.DESCRIPTION' | translate}}" ng-model="category.description"></textarea>
            </div>

        </div>
    </div>
    <div class="modal-footer">
        <a class="btn btn-grey" ng-click="cancel()" tooltip="{{ 'TOOLTIP.CANCEL' | translate }}"><i
                class="fa fa-ban"></i></a>
        <button type="submit" class="btn btn-success" tooltip="{{ 'TOOLTIP.SAVE_AND_EXIT' | translate }}"><i
                class="fa fa-check-square-o"></i></button>
    </div>
</form>

During the editing process, due to two-way data binding, any modifications made to the original object are reflected instantly. Therefore, if changes are canceled, the object will still appear altered.

Considering this circumstance, I attempted to research $apply and copy, but I am uncertain about their implementation in this context.

What is the recommended approach in the aforementioned scenario? How do you manage such situations?

Answer №1

To make changes to a duplicate, you can utilize the following code snippet:

 $scope.duplicate = angular.copy(original);

Once you have verified the server update, you can merge the duplicate with the original:

 angular.extend( original, $scope.duplicate);

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

Displaying a highchart once a form has been submitted in a separate file

Can someone assist with this issue? I am trying to display a Highchart from file_2 in file_1 using PHP, jQuery, and AJAX. Below is the script I am working with: SCR_test02.php <?php require "function.inc.php"; //require "showscr.php"; include "c ...

Vue - Seamlessly Editing and Creating Content Together

When using Laravel, I am attempting to pass data to a Vue component. Depending on whether the user enters the component through an edit URL or a create URL, we send either an array of data or null. Here is an example of how this process works: Blade view ...

adding a new div to the bottom of a row that is being created on the fly

I encountered an issue where rows are created dynamically and I needed to add a div at the end of each row. Despite trying various methods, I faced difficulties as adding the div resulted in extra divs being added to all previous rows whenever a new row wa ...

Backend data not displaying on HTML page

I am currently working on an Angular 8 application where I have a service dedicated to fetching courses from an API endpoint. The service method that I'm using looks like this: loadCourseById(courseId: number) { return this.http.get<Cours ...

What is causing ngdocs to produce zero files?

I have created a basic project to experiment with grunt-ngdocs (https://www.npmjs.org/package/grunt-ngdocs). But, for some reason, when I attempt to generate documentation, it fails to recognize any comments. Why is this happening? Can someone offer assist ...

Is it possible for search engines like google to index Javascript content that is stored within divs and loaded onto the page?

My website utilizes JavaScript to dynamically add content to div elements, like so: <script> //This content is generated by PHP var contents = [ "Item 1", "Item 2" ]; //Display the first item document.getElementById( "item" ).textCo ...

Tips for Utilizing jQuery each Loop

I am attempting to create a foreach loop that will iterate through hidden values on the page, compare them with an external API using Ajax, and display the API results in a < ul > for example. Sample model ITEM1 metavalue (which needs to be che ...

Retrieving individual data elements from an array with the help of the .find() method

I am struggling to display specific details of an object within an array by using .find() method, but I keep receiving undefined as the output. Below is the code snippet where I attempted this, when I log the ID, I can see a value, however, when I try to ...

Serving Files in Express JS: the benefits of serving files directly from memory compared to serving static

Should I keep images and other assets in memory or serve them from static assets? Will often-requested static assets be stored in memory? Does anyone have insight into the performance implications of this decision? ...

Error in Three.js: "Framebuffer and active Texture causing a feedback loop" - Issue with Reflection Rendering

I am currently utilizing a CubeCamera along with WebGLCubeRenderTarget to capture the surrounding reflection in a manner similar to the example found at this link - https://threejs.org/examples/#webgl_materials_cubemap_dynamic However, I am encountering a ...

When json.parse encounters an undefined value at position 1

Currently, I am diving into learning express.js and my latest project involves creating a web app that can convert cryptocurrency to Fiat currency. Things have been progressing smoothly so far, but I've hit a roadblock when attempting to use json.pars ...

How can I generate codegen types using typeDefs?

I have been exploring the capabilities of graphql-codegen to automatically generate TypeScript types from my GraphQL type definitions. However, I encountered an issue where I received the following error message: Failed to load schema from code file " ...

Display information using AngularJS within the Ionic framework

I am attempting to display a variable that is within a for loop. Here is my code where I store the value of $scope.datosTuto[i].Nombre in a variable. When I use an alert to print $scope.NombTuto, I can see the data but I want to display it on my HTML page. ...

How to extract a JavaScript object from an array using a specific field

When dealing with an array of objects, my goal is to choose the object that has the highest value in one of its fields. I understand how to select the value itself: Math.max.apply(Math, list.map(function (o) { return o.DisplayAQI; })) ... but I am unsur ...

Sorting through an array of objects nested within another array of objects

I'm currently working on a MERN app where I retrieve all albums using axios. This is the structure of the data: [ { title: "", artist: "", reviews: [ { username: "", comment: "", }, { ...

Save the current active tab when refreshing the page

Struggling to find a way for the browser to remember the last active tab but haven't been successful. function ShowMyDiv(Obj){ var elements = document.getElementsByTagName('div'); for (var i = 0; i < elements.length; i++) if(element ...

What could be causing the error message about jQuery not being defined in this bookmarklet code, even though jQuery is already included

As I work on creating a bookmarklet, I encountered an issue with the code below. When I visit a page, it initially gives an error message saying "jQuery is not defined". However, upon clicking it again, the bookmarklet functions perfectly. var qrcodetog ...

The angular view is lacking a CSS class

index.html: <div ng-view="myview.html"></div> myview.html: <table class="table table-striped table-hover"> <tr> <td>Name</td> <td>Product</td> </tr> <tr ng-repeat="deal in deals" class="clickableR ...

Transmit an array of JavaScript objects using Email

Within the code layout provided with this post, I have executed various operations in JavaScript which resulted in an array of objects named MyObjects. Each object within MyObjects contains properties for Name and Phone, structured as follows: MyObject ...

The error message indicates that the property 'current' is not found in the type '[boolean, Dispatch<SetStateAction<boolean>>]'

During my React/Typescript project, I encountered an issue involving cursor animations. While researching the topic, I stumbled upon a CodePen (Animated Cursor React Component) that functioned perfectly. However, when attempting to convert it into a Types ...