AngularJS application encountering an undefined variable within the scope

I'm attempting to set a Boolean property on an element within my array object that is part of my scope.

When I use the code below and try to set tasks[id].deleted = true, I encounter the following error:

angular.js:12798 TypeError: Cannot set property 'deleted' of undefined
at Scope.$scope.delete (main.js:54)

What am I doing wrong?

Here's the entirety of my code file:

angular.module('ngMaterialTaskListApp')
.controller('MainCtrl', function ($scope, $mdDialog, TaskService) {

    // Model from which View populates data
    $scope.tasks = [];
    console.log($scope.tasks);

    $scope.showAddDialog = function (ev) {
        $mdDialog.show({
            controller: DialogController,
            templateUrl: '../views/add-dialog-template.html',
            parent: angular.element(document.body),
            targetEvent: ev,
            clickOutsideToClose: true,
            fullscreen: true, //Only for xs and sm screen sizes
            locals: { //For DialogController, as tasks
                tasks: $scope.tasks
            }
        });
    };
    /*----------- Function to delete items onClick of delete icon -----------*/
    $scope.delete = function (id) {
        console.log($scope.tasks[id]);
        console.log(id);
        // console.log($scope.tasks[id].name);
        $scope.tasks[id].deleted = true;
    };

    /*----------- DialogController function -----------*/
    function DialogController($scope, $mdDialog, tasks) {
        $scope.task = {};
        $scope.hide = function () {
            $mdDialog.hide();
            //TODO Add a message as to what happened
        };
        $scope.cancel = function () {
            $mdDialog.cancel();
            //TODO Add a message as to what happened
        };
        /*----------- Method show the add dialog -----------*/
        $scope.addData = function () {
            if (null !== $scope.task.name && null !== $scope.task.description) {
                /*----------- Using moment.js to parse date and time -----------*/
                $scope.task.date = moment($scope.task.date, '').format('DD MMM YYYY');
                $scope.task.time = moment($scope.task.time, '').format('h:mm a');
                $scope.task.done = false; // Every new task is pending!
                $scope.task.deleted = false; // Every new task exists!
                var GlobalID = Date.now();
                console.log(GlobalID);
                $scope.task.id = GlobalID;
                /*----------- Performing http POST -----------*/
                TaskService.postTask($scope.task);
                /*----------- Pushing to tasks object in $scope of MainCtrl -----------*/
                // Have to update tasks again
                tasks.push($scope.task);
                $scope.hide();
                console.log(tasks); //DEBUGGING
            } else {
                //TODO ADD INVALID/NULL DATA WARNING
            }
        };
    };
    // DEPRECATED - USED FOR DATA WHEN SERVER NOT AVAILABLE
    TaskService.getTasks().then(function (response) {
        $scope.tasks = response.data.tasks;
    }, function (error) {
        console.log(error + "This");
    });
    //USING THIS TO GET DATA FROM SERVER
    TaskService.getAllTasks().then(function (response) {
        // console.log(response.data);
        $scope.tasks = response.data;
        console.log($scope.tasks);
    });
});

Answer №1

What is your proficiency level in html? I assume it looks something like this within a button in ng-repeat:

ng-click="delete(task.id)"

Consider changing it to the following format:

ng-click="delete($index)"

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

When utilizing ng-views within PhoneGap, receiving the origin is restricted due to the Access-Control-Allow-Origin policy

Having trouble getting ng-views to function properly in an Android phone app. When attempting to navigate to one of the views via a hyperlink, I encounter the error message: "Origin is not allowed by Access-Control-Allow-Origin" I have made attempts to m ...

Error: The "res.json" method is not defined in CustomerComponent

FetchData(){ this.http.get("http://localhost:3000/Customers") .subscribe(data=>this.OnSuccess(data),data=>this.OnError(data)); } OnError(data:any){ console.debug(data.json()); } OnSuccess(data:any){ this.FetchData(); } SuccessGe ...

Redirecting the socket.io client to the Heroku service

Recently, I developed a real-time chat application using socket.io, Node.JS, and express. It was functional on my local server but now I want to connect it to an existing Heroku service instead. How can I achieve this? Once I tried the following code, va ...

The child module invokes a function within the parent module and retrieves a result

Guardian XML <tr [onSumWeights]="sumWeights" > Algorithm sumWeights(): number { return // Calculate total value of all weights } Offspring @Input() onTotalWeights: () => number; canMakeChanges() { return this.onTota ...

What is the best way to anticipate a return phone call?

Looking to retrieve the largest date from a folder by reading its contents. https://i.stack.imgur.com/KYren.png Here is the code snippet to read the folder, extract filenames, and determine the largest date (excluding today): async function getLastDate ...

AngularJS SmartyUI position not dynamically updating on SmartyStreets plugin

In my angularJS application, I am utilizing SmartyStreets' LiveAddress for address validation and autofilling two fields in a form. After the user submits the form, a message (either success or failure) is displayed in a div above the form. However, t ...

npm is consolidating all dependencies and their sub-dependencies into a single unified directory

My project has a package.json file with approximately 20 dependencies. Upon running npm install, all the dependencies and sub-dependencies end up in the main node_modules directory, resulting in hundreds of modules rather than just my intended 20. The sub- ...

Guide on uploading a file to Amazon Glacier with Node.js

While browsing through the Amazon AWS documentation, I stumbled upon this helpful example. var glacier = new AWS.Glacier(), vaultName = 'YOUR_VAULT_NAME', buffer = new Buffer(2.5 * 1024 * 1024); // 2.5MB buffer var params = {vaultName: ...

What are the best techniques for achieving flawless ring geometry in three.js?

I'm struggling to achieve perfect ring geometry in three.js, similar to the image here: https://i.sstatic.net/ArxKa.png After spending over a day troubleshooting, my code currently looks like this: var scene = new THREE.Scene(); var camera = new TH ...

Injecting windows in Angular

Is there a way to prevent the Angular instance from injecting into the global (window) scope when required and bundled with webpack or any other module bundler? Upon inspection, I discovered that the current main Javascript file in the Angular npm package ...

Adding next-auth middleware on top of nextjs middleware in Nextjs implementation

I am in need of the nextjs middleware to be activated for two distinct paths: Firstly, to serve as a protection against unauthorized access by utilizing next-auth. Secondly, to redirect authorized users from specific pages. For example, if an authorized u ...

The element vanishes from sight after being detached and re-appended

Currently, I am utilizing hQuery's draggable and droppable features. My goal is to move an element from its original parent to its new dropped parent after dragging it. However, when I detach and append the element, it seems to disappear! What could ...

Fiddle demonstrates HTML functionality, while local testing is unsuccessful

Currently, I am in the process of creating an image slider and attempting to run it on my personal computer. However, upon doing so, I have encountered a problem where the page is not rendering correctly. Additionally, I receive an ActiveX warning message ...

Transform a JQuery function using the each method into vanilla JavaScript

Seeking assistance. I have developed a multilingual static site using JQuery and JSON, but now I want to switch to simple JS. Most of the code is ready, except for the portion commented out in the JS (which works fine with JQuery). var language, transla ...

Discover Xml information or Json object displayed as XML tree in Html using Javascript

Looking for a way to display my JSON object or XML data in HTML similar to how React does it. I found this component on GitHub: https://github.com/marushkevych/xml-display-component, but I prefer not to mix JavaScript and React.js. Can anyone offer some gu ...

I'm having issues with the functionality of my code inside the ng-template and ngIf. What could be

I am facing an issue with my method that is supposed to display the specified HTML content. However, it seems like the ngIf condition within the code block is not functioning correctly. Can someone help me understand why the ngIf statement is being ignored ...

Updating meta tags dynamically in Angular Universal with content changes

Hello, I'm encountering an issue with a dynamic blog page. I am trying to update meta tags using data fetched from the page. Here's the code snippet: getBlogPost() { this.http.get(...) .subscribe(result => { this.blogPost = re ...

AngularTS - Using $apply stops the controller from initializing

Every time I launch the application, the angular {{ }} tags remain visible. Removing $scope.$apply eliminates the braces and displays the correct value. I am utilizing Angular with Typescript. Controller: module Application.Controllers { export class Te ...

Parsing a JSON object in JavaScript: A step-by-step guide

Looking for assistance on how to parse the JSON object below: { "info": [ { "systemIp": "192.168.1.1", "status": "done 956" }, { "systemIp": "192.153.1.1", "status": "done" } ] } Does anyone have a solution using Javascript or jQuery? The desired output ...

Can anyone tell me the best way to access the name attribute of an HTML element in TypeScript?

Currently, my code is utilizing the name attribute to verify whether the user has entered information in a specific field and validating the input. However, I am facing an issue where the submit button remains active even if there are empty fields presen ...