Enhance and modify data with AngularJS, while also incorporating new information into the

Working on a feature where Worklists can be added and edited or deleted from local storage.

Encountering an issue where after editing a worklist, it cannot be added anymore as it updates the existing worklist data that was selected for editing. (the edited data should also reflect in the local storage)

Check out the Fiddle: https://jsfiddle.net/3gosnxny/3/

Html:

<div ng-app="sandbox">
    <div>

        <div ng-controller="workController">

            <form name="commentForm" method="post">

                <div class="col-xs-12 col-sm-12 col-md-12">
                    <label for="workOne">Work One</label>
                    <input class="form-control isRequired" type="text" id="workOne" name="skillsMain" ng-model="workOne" placeholder="Enter Work">
                </div>

                <div class="col-xs-12 col-sm-6 col-md-6 pull-right">
                    <button class="btn btn-default" type="submit" value="Add" ng-click="add()">SAVE</button>
                </div>

            </form>
            <div class="clearfix"></div>

            <div class="content_area">
                <h4>WorkList</h4>
                <hr/>
                <ul class="ItemSkills">
                    <li ng-repeat="items in workList">
                        <span class="hidden-xs hidden-sm hidden-md hidden-lg">{{items.id = $index}}</span>
                        <h4>{{items.workOne}}</h4>
                        <div class="btn_main">
                            <div class="btn" ng-click="selectEdit(items.id)">Edit</div> |
                            <div class="btn" ng-click="del(items.id)">Delete</div>
                        </div>
                    </li>
                </ul>
                <div class="clearfix"></div>
            </div>

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

CSS:

.ItemSkills h4 {
    display: inline - block;
}

.btn_main {
    display: inline - block;
}

ANGULAR CODE / Script:

(function() {
    'use strict';

    var App = angular.module('sandbox', ['LocalStorageModule']);


    App.value('workList', []);
    // Skills List
    App.controller('workController', ['$scope', 'localStorageService', 'workList', function($scope, localStorageService, workList) {

        // <!-- Populate table with products data -->
        $scope.workList = workList;
        $scope.storage = localStorageService;

        // <!-- Delete function -->
        $scope.del = function(id) {
            var result = confirm('Are you sure?');
            if (result === true) {
                var index = getSelectedIndex(id);
                $scope.workList.splice(index, 1);
            };
        };

        // <!-- Select the row of data and update the form function -->
        $scope.selectEdit = function(id) {
            var index = getSelectedIndex(id);
            var product = $scope.workList[index];
            $scope.id = product.id;
            $scope.workOne = product.workOne;
        };

        // <!-- Add a new product function -->
        $scope.add = function(id) {
            console.log($scope.storage);
            $('.isRequired').each(function(i, obj) {
                if ($(this).val() == "") {
                    $(this).addClass("errorinput");
                } else {
                    $(this).removeClass("errorinput");
                }
            });

            var index = getSelectedIndex($scope.id);
            if (!index == "") {
                //If index is not available do Save
                if (!$scope.workOne == "") {
                    $scope.workList.push({
                        workOne: $scope.workOne
                    });
                    // Save Data to storage
                    $scope.storage.workStore = $scope.workList;

                    // <!-- Resets the form -->
                    $scope.workOne = '';
                }
            } else {
                //If index is available do Edit
                $scope.workList[index].workOne = $scope.workOne;
                // <!-- Resets the form -->
                $scope.workOne = '';
            }

        };

        // <!-- Function finds unique product data based on its id -->
        function getSelectedIndex(id) {
            for (var i = 0; i < $scope.workList.length; i++)
                if ($scope.workList[i].id == id)
                    return i;
            return -1;
        };

    }]);

})();

Live JsFiddle: https://jsfiddle.net/3gosnxny/3/

Answer №1

UPDATED ANGULAR SCRIPT:

(function() {
    'use strict';

    var App = angular.module('sandbox', ['LocalStorageModule']);

    App.value('workList', []);
    
    // List of skills
    App.controller('workController', ['$scope', 'localStorageService', 'workList', function($scope, localStorageService, workList){

        $scope.workList = workList;
        $scope.storage = localStorageService;

        $scope.del = function(id){
            var result = confirm('Are you sure?');
            if (result===true){ 
                var index = getSelectedIndex(id);
                $scope.workList.splice(index, 1);
            };
        };

        $scope.selectEdit = function(id){
            var index = getSelectedIndex(id);
            var product = $scope.workList[index];
            $scope.id = product.id;
            $scope.workOne = product.workOne;

        };

        $scope.add = function(){
            $('.isRequired').each(function(i, obj) {
                if($(this).val() == ""){
                    $(this).addClass("errorinput");
                }
                else{ $(this).removeClass("errorinput"); }
            });
            
            if($scope.id == undefined || $scope.id == '-1') {
               var index = '-1';
            } else {            
              var index = getSelectedIndex($scope.id);
              $scope.id = '-1';
            }

            if(index == "-1"){
                if(!$scope.workOne == ""){
                    $scope.workList.push({
                        workOne:$scope.workOne
                    });
                    $scope.storage.workStore = $scope.workList;
                    $scope.workOne = '';
                }
            }
            else{
                $scope.workList[index].workOne = $scope.workOne;
                $scope.workOne = '';
            }

        };

        function getSelectedIndex(id){
            for(var i=0; i<$scope.workList.length; i++)
                if($scope.workList[i].id==id)
                    return i;
            return -1; 
        };

    }]);

})();

Your code has been successfully updated.

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

Access to PHP script (IF) unattainable following a POST occurrence

I'm completely new at this. I am attempting to create a contact form using HTML5 and PHP mail function, but I am facing an issue with my form action pointing to contacto.php. After submitting the form, it seems to be skipping over the IF condition wi ...

What are the steps to turn off response data compression in an Express server?

How can I receive the 'Content-Length' response from the server without gzip compression enabled? I am using a compression middleware for this purpose: const shouldCompress = (req, res) => { if(req.headers['x-no-comprassion']) { ...

I am encountering a challenge retrieving the ID via AJAX from the view to the controller. However, the ID is successfully displaying in the alert

In the view page code below, I am trying to send an ID through Ajax but it is not posting in the controller. The goal is to replace one question at a time fetching from the database. $(document).ready(function() { $("#next").click(function() { ...

Altering the backdrop upon hovering over an element

As a beginner in Javascript and Jquery, I am working on creating an interactive feature where hovering over one element changes the background image in another column. I have managed to write the function, but now I want to add an animation to the image tr ...

Switch Selector for React Native

Although it may seem simple, I'm having trouble getting a function to automatically switch between the "user" and "business" options on the switch selector without requiring manual input from the user. I attempted to use: const switchRef = useRef(nu ...

Implementing Twitter Login with Vue, Vuex, and Firebase

Exploring a Twitter login option for my sports social media dashboard project, I followed a helpful tutorial. While I've successfully implemented the HelloWorld component and retained the app.vue and main.js components, I encountered an error stating ...

Issues with Javascript Arrays not adding objects with duplicate values

When objects have arrays with the same values, only one of them is considered. For example: data[2018][2][25] <-- this one gets ignored by the object data[2018][2][22] Sample Code: var date = new Date(); var data = {}; <?php $eventsNum = 3> &l ...

Using JQuery to iterate through every unique div id in the HTML document

i am attempting to utilize jquery to iterate through each div tag that has an id of "rate". The goal is for jquery to execute a function on the individual divs. Here is my code snippet: information.html <html> <input class="rate" type="hidden ...

Modal containing react-select dropdown opens successfully

I am currently facing an issue with my custom modal that contains 2 react-select components. The modal body is set up to auto scroll when the content exceeds its size, but the problem arises when the dropdowns of the react-select components open within the ...

The default export (imported as 'Vue') could not be located within the 'vue' module in Vue 3 and Laravel

I'm currently in the process of building a project that combines Laravel 8 and Vue JS 3. I've set everything up, but whenever I try running `npm run watch`, I encounter an error message similar to the one below. Despite looking through various fo ...

Guide to utilizing various Nodelists using the forEach function

I'm currently developing an online store project that includes a shopping cart feature. My goal is to send a POST request to the server with the items selected by the user in the cart. I have initialized an empty array and I have 3 Nodelists containin ...

Issue occurred in module.js:341 while attempting to include android platform to ionic using command line

For my hybrid app development using the Ionic framework, I made sure to install all required dependencies like node.js and cordova. Following their Getting started guide, I reached step 3 which instructs running this command within the app directory: > ...

Experiencing difficulties with a cross-domain jQuery/AJAX service request

After extensively researching various threads both on this platform and elsewhere, I have been trying to successfully execute a cross-domain AJAX call. The scenario involves a Restful WCF service that simply returns a boolean value. The service is configur ...

implementing a JavaScript function and declaring a variable from an HTML source

On my webpage, I have a feature that gathers a large amount of data using jQuery. My goal is to limit the number of results displayed by changing the shown results dynamically to create a false-page effect. This functionality is all handled through a singl ...

Find all objects in an array of objects that contain at least one value that matches a given string

I am currently integrating search functionality in my application. The UI search results are generated from an array of objects. My goal is to loop through the name, custNumber, and sneak values in each object and display only the ones that contain a subst ...

Having issues with installing <package> using npm

I'm currently following a tutorial to install the Angular package in my project. My system already has npm (4.0.5) and node (6.9.2) installed. I navigated to my project folder and executed the following command: npm install angular Despite runnin ...

Text Parallax Effect

For my website, I am interested in incorporating a unique parallax effect. Instead of just fixing a background image and allowing scrolling over it, I want to apply this effect to all of the content on my site. The website consists of a single page with m ...

Showcasing certain elements as the user scrolls

Looking for a way to display an element (such as a div) when the user scrolls without using JQuery? Here's an example that tries to achieve this: var scroll = document.body.scrollTop; var divLis = document.querySelectorAll("div"); for(let i = 0; i ...

What is the best way to extend a class in NestJS from another class?

I've encountered an issue while attempting to extend a class service from another class service in NestJS and utilize DI to load it in a third service. The error message I'm receiving from Nest is: Error: Nest can't resolve dependencies of ...

Tips for sending information to a JavaScript variable through AJAX requests

Hello there, I'm currently working on a project that involves posting data stored in a JavaScript variable using AJAX. Can anyone assist me with the correct syntax for this process? <div class="container-fluid"> <div class="card shadow m ...