Execute parent controller method using modalInstance.result.then() AngularJS

Issue

I’m trying run a class method (in the controller that creates my $uibModal) once the modal’s “okay” button has been pressed. My understanding is that the modalInstance is returning a modal object from the component, and therein lies my problem… how can I interact with the parent controller instead of the component?

Example:

modalInstance.result.then(function () {
      // if close() called in component, do this in the parent controller
      this.users.splice(this.users.indexOf(user), 1);    
   }, function () {
      // if dissmised, do this
      console.log('modal-component dismissed at: ' + new Date());
});

This throws an error:

TypeError: Cannot read property ‘users’ of undefined

Here is a Plunker with the key items:
https://plnkr.co/edit/ZY3Kr9g3MuT1AxsQKfsj?p=catalogue

AngularJS 1.6, using Angular Fullstack Generator 4.2.3

I’ve followed this documentation: https://angular-ui.github.io/bootstrap/ to create a modal component and the modal works great. But I can’t splice my array of users no matter what I try. Please help!

Solution

Might be because of incorrectly bound this in your callback, try binding it explicitly to parent enclosing scope using =>:

modalInstance.result.then(() => {
      // if close() called in component, do this in the parent controller
      this.users.splice(this.users.indexOf(user), 1);    
   }, function () {
      // if dissmised, do this
      console.log('modal-component dismissed at: ' + new Date());
});

Answered By – Karen Grigoryan

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.