Encountering issues with accessing 'this' items in the confirmation function of Angular Material's $mdDialog

Attempting to utilize the confirm function within an Angular Material $mdDialog in order to clear an array and then log it to the console is proving problematic. There appears to be an issue with accessing 'this' objects, arrays, expressions, and functions within the $mdDialog function itself. The console is indicating that whatever item is being referenced is undefined, even if it has been used in other controller functions.

Is there a compatibility problem between the $mdDialog directive and the controllerAs syntax?

-

Controller:

app.controller('notificationsController', function($scope, $state, $http, $document, $mdDialog, $filter, $timeout) {

this.selectedNotification = null;
this.notifications = [
    {
        title: 'Notification One',
        description: 'Description...',
        time: '2017-10-27T16:39:32+00:00',
        importance: 'Low',
        read: false
    },

    etc...

$scope.clearNotifications = function(ev) {
    var confirm = $mdDialog.confirm()
        .parent(angular.element('body'))
        .clickOutsideToClose(true)
        .title('Are you sure you want to clear all notifications?')
        .textContent('This action cannot be undone.')
        .ariaLabel('Confirm notifications list clearance')
        .ok('Yes')
        .cancel('No')
        .targetEvent(ev)

    $mdDialog.show(confirm).then(function() {
        $scope.status = 'All notifications deleted';
        console.log($scope.status);
        this.notifications.length = 0;
        console.log(this.notifications);
    }, function() {
        $scope.status = 'Notifications list not cleared';
        console.log($scope.status);
    })
}

Answer №1

The usage of this within this context is crucial:

$mdDialog.show(confirm).then(function() {
    ...
    this.notifications.length = 0; // <---- this line
    ...
}, function() {
    ...
})

Here, the reference to this points to the callback function of the promise generated by $mdDialog.show(). To access the controller's notifications member, it's necessary to store a reference to the controller's this in a separate variable:

app.controller('notificationsController', function($scope, $state,           
$http, $document, $mdDialog, $filter, $timeout) {

  var _this = this; // <--- Now we have _this representing the controller
  this.notifications = [
  {
    title: 'Notification One',
    description: 'Description...',
    time: '2017-10-27T16:39:32+00:00',
    importance: 'Low',
    read: false
  },

etc...

$scope.clearNotifications = function(ev) {
  ...

  $mdDialog.show(confirm).then(function() {
    ...
    _this.notifications.length = 0; //<--- Using _this instead of this
    ...
  }, function() {
    ...
  })
}

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

Is it possible to configure a redirect to HTTPS using ng-view for a particular route?

I am currently developing a project using angular 1.5.0-rc0. My configuration involves using angular-route with ng-view, set up as follows: app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) { ...

Content within innerHTML not appearing on the screen

I'm facing an issue with displaying an error message when the user enters incorrect username or password. The message should pop up below the sign-in box, but it's not showing up for some reason. Can anyone help me figure out why? Here is my cod ...

Converting a string to a number, even if it contains non-numeric

Is there a built-in function that can directly convert a string containing non-numeric characters to a number in JavaScript, without the need for using str.substring() followed by parseInt()? For instance, how can I efficiently convert the string x1 to th ...

Property list is incomplete and requires an "after" parameter

This particular piece of code is generating the following error message: missing : after property list exactly where the error comment is placed. $("#jquery_jplayer_1-<?php echo $key.'-'.$j; ?>").jPlayer({ ready: function () { ...

Updating a particular column in a table with Jquery

In this table : $('#listview-table tr').each(function() { var status_id = $(this).find(".listViewEntryValue").$('[data-name~="cf_1525"]').text(); alert(status_id); }); <table id="listview-table" class="table listv ...

Ways to tally elements that have been dynamically loaded onto the webpage through AJAX requests

My page has a dynamic region that is continuously updated using jQuery's .ajax and .load methods. In order to submit the form, there need to be at least 3 of these 'regions', so I have to keep track of the number of DIVs with a specific cla ...

Updating parent model with select list value using a directive

Seeking help with a directive that produces a select list. I'm trying to pass in the id and value keys of the object for reusability. However, the list isn't binding to its parent model when it's updated. Any ideas on why this might be happe ...

Redux application is not functioning properly

I followed the official documentation to create a Redux app at http://redux.js.org/docs/basics/ but it's not working as expected. I have organized my code into four files: store, reducers, actions, and build. actions.js: export const ADD_TODO = &apo ...

I am looking to retrieve information from mongodb and then transform it into a JSON object using node.js. Can you guide

I am on a mission to retrieve data from a MongoDB database and transform it into a JSON object in Node.js. The goal is to be able to easily manipulate this data as if it were a simple JSON object. Here's the current code snippet I'm working with: ...

Secure your password with Vue JS encryption techniques

I am looking for a way to safely encrypt passwords on my Vue JS web application. While I already have a hash encrypter set up on the API, I am running into an issue where the password is displayed as plain text during the signin or signup call. Any recom ...

What is the method to determine the overall size of a webpage using the Google PageSpeed API?

"analytics": { "cssResponseBytes": "333 kB", "htmlResponseBytes": "269 kB", "imageResponseBytes": "3.35 MB", "javascriptResponseBytes": "2.29 MB", "numberCssResources": 2, "numberHosts": 80, "numberJsResources": 72, "numberR ...

Loop through each current value in an ng-repeat directive and use it in an

I'm facing a simple issue that doesn't seem to have an easy fix. I have a ng-repeat set up like this <p ng-repeat="title in Menu.data[Menu.selected]"> {{ title }} </p> Now, I want to add an onclick event so I adjusted i ...

Can we prevent a component from being mounted every time it is rendered by its parent component?

Is it possible to render the Child component within the Father component without mounting it and resetting its states when the Father component is rendered? I attempted to use the useMemo hook to render the Child component, but it still mounts the compone ...

Conceal a div element using a button through JavaScript

I've been scouring various online resources for solutions, including Stack Overflow and W3Schools, but I haven't had any luck so far. Here's a simplified version of my current code: <script language="javascript"> function remove() ...

Invoking code behind functions through ajax requests to dynamically display items one by one

I'm currently working with calling code behind functions from an ajax call. I have recently developed a method called Post, which returns a list of values. My goal is to verify these values from the client side by displaying them in an alert message. ...

Creating a map in Ionic with updated latitude and longitude coordinates

I'm currently facing an issue where I am inputting the correct latitude and longitude values for the map, but it is still displaying an outdated map with old coordinates. I believe there is a mistake in my implementation, but I haven't been able ...

Using Regular Expression to verify the presence of numbers and spaces

Currently, I have implemented a regular expression that ensures my string contains 5 digits. While this regex works flawlessly, I now also require it to allow white spaces: both "123 45" and "12345" should meet the criteria. string.match(/^\d{5}$/g); ...

Guidelines for attaining seamless motion animation utilizing devicemotion rotationRate information

I am utilizing the rotationRate data obtained from the devicemotion eventListener to manipulate a three.js scene by tilting. The scene does respond to the data accurately in terms of angle adjustments, but it produces an unsmooth motion effect. Is there a ...

The specified property 'length' is not found on type OkPacket within the mysql2 module

In my code example below, I am simply showcasing a specific scenario: this.getCode = (code: string): Promise<codeObject | false> => { return new Promise((resolve, reject) => { pool.query('SELECT * FROM ?? WHERE code = ...

Utilize $stateParams to dynamically generate a title

When I click a link to our 'count' page, I can pass a router parameter with the following code: $state.go('count', {targetName: object.name}) The router is set up to recognize this parameter in the URL: url: '/count/:targetName& ...