VladimirSD VladimirSD - 6 months ago 11
AngularJS Question

Why doesn't "this.function" work in a modal popup but $scope does?

In the modal controller I was trying to use
this.cancel = function () .... but the function never got called.
I had to change it to $scope.cancel .... for it to work and I'm trying to understand why that is.

this."whatever" does work in the main controller

Code snippet :

function MainController($uibModal) {
//this works
this.popup = function () {
$uibModal.open({
controller: 'PopupCtrl',
templateUrl: 'myctrl.html'
});
};
}

function PopupController($scope, $uibModalInstance) {

//"this.cancel" does not work, need to use $scope
$scope.cancel = function (){
$uibModalInstance.dismiss();
};
//"this" wont work
this.ok = function (){
$uibModalInstance.dismiss();
};
}


I've created a Plunker to show the example

http://plnkr.co/edit/nMBe6SqXzicxkHNT5JdT

Answer

I forked your plunker. This is my version

    this.popup = function () {
         $uibModal.open({
            controller: 'PopupCtrl as popupctrl',
            templateUrl: 'myctrl.html'

    });

The key here is the syntax "PopupCtrl as popupctrl"
popupctrl is the reference to your modal controller. In the view I did this:

ng-click="popupctrl.ok()"

Note that I used that "reference".