Search code examples
javascriptangularjsangularjs-controlleras

How to use controllerAs syntax with AngularJS modal in case of "modal in the same controller" approach


This is my modal function:

vm.openUpdateStateModal = function (nextState, idea) {
  $scope.nextState = nextState;
  $scope.idea = idea;
  $scope.modalWindowOpen = true;

  $scope.modalInstance = $modal.open({
    templateUrl: 'updateStateModal',
    windowClass: 'updateStateModal',
    scope: $scope
  });

  $scope.modalInstance.result.then(function () {
    $scope.updateState(nextState, idea);
  });

  $scope.modalInstance.result.finally(function () {
    $scope.modalWindowOpen = false;
  });
};

I don't want to have another controller for my modal, that's why i just give my $scope as parameter, instead of mapping the parameters separately. So on the view side, i can use all the $scope variables.

Yesterday i updated my controller to the controllerAs syntax like this:

angular.module('app')
  .controller('IdeaCtrl', function ($scope, ...) {

    var vm = this;
    ...

Now how can i adapt this modal function to this new syntax? The challenge for me is: I reuse the view of modal window more than once, also on my main view (without modal). And this view is already adapted to the new syntax "vm.data" instead of "data".

I tried to give my vm as scope, it did not work. How can i handle this?

EDIT:

I have changed my function to this:

vm.openUpdateStateModal = function (nextState, idea) {
  $scope.nextState = nextState;
  $scope.idea = idea;
  $scope.modalWindowOpen = true;

  $scope.modalInstance = $modal.open({
    templateUrl: 'updateStateModal',
    windowClass: 'updateStateModal',
    controller: 'IdeaCtrl as vm',
    scope: $scope
  });

  $scope.modalInstance.result.then(function () {
    $scope.updateState(nextState, idea);
  });

  $scope.modalInstance.result.finally(function () {
    $scope.modalWindowOpen = false;
  });
};

So i added this line:

controller: 'IdeaCtrl as vm',

Now it seems ok. But i still i have to use the idea and nextstate variables from the scope. How can i use also those from vm?


Solution

  • Ok i have made it like this:

    vm.openUpdateStateModal = function (nextState, idea) {
      vm.modalWindowOpen = true;
      vm.nextState = nextState;
      $scope.idea = idea;
    
      vm.modalInstance = $modal.open({
        templateUrl: 'updateStateModal',
        windowClass: 'updateStateModal',
        scope: $scope
      });
    
      vm.modalInstance.result.then(function () {
        vm.updateState(nextState, idea);
      });
    
      vm.modalInstance.result.finally(function () {
        vm.modalWindowOpen = false;
      });
    };
    

    On the view side, i use the idea from scope, and the other variables from vm. I have to use idea directly from scope, since i have sth like this on my main view:

    ng-repeat="idea in vm.awesomeIdeas
    

    ..and i cannot define sth like this:

    ng-repeat="vm.idea in vm.awesomeIdeas