4

I am writing an app with AngularJS 1.5.3. I am using the $ionicModal service to show modals to my users.

I want to move my code into the 'controller as' syntax but I am not sure how to do that with the $ionicModal service.

Here is my controller code:

(function () {
    "use strict";

    angular
        .module('myApp')
        .controller('myController', myController);

    myController.$inject = [
        '$scope',
        '$ionicModal',
        'myService'
    ];

    function myController($scope, $ionicModal, myService) {

        $scope.data = myService.data;

        $scope.openModal = openModal;

        $ionicModal.fromTemplateUrl('./myPath/modal.html', function ($ionicModal) {
            $scope.modal = $ionicModal;
        }, {
            scope: $scope,
            animation: 'slide-in-up'
        });

        $scope.$on('$destroy', function () {
            $scope.modal.remove();
        });

        function openModal() {
            $scope.modal.show();
        };

    }

})();
user1261710
  • 2,539
  • 5
  • 41
  • 72

2 Answers2

3

I want to move my code into the 'controller as' syntax but I am not sure how to do that with the $ionicModal service.

Short answer

NO

Detailed answer

Ionic creates modal scope by calling:

var scope = options.scope && options.scope.$new() || $rootScope.$new(true);

When you use ControllerAs for your root controller suppose you have vm instance of the scope (a.e vm = this;).

vm is not a scope!!!.

vm is only object and there is no scope inheritance, it doesn't have .$new() method

So we cannot write {scope: vm} but only {scope: $scope}


For sure you can play with Ionic code but it can lead to unexpected behavior

Community
  • 1
  • 1
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
1

Ionic modal options may include parent scope as scope option,

scope The scope to be a child of. Default: creates a child of $rootScope.

It is similar to UI Bootstrap modal in this regard. So it should use $scope any way to set up proper scope hierarchy. There's nothing wrong with using $scope together with controllerAs syntax when necessary.

Considering that the controller has $ctrl controllerAs identifier, it should be something like:

function myController($scope, $ionicModal, myService) {
    var self = this; // === $scope.$ctrl
    self.data = myService.data;
    self.openModal = openModal;

    $ionicModal.fromTemplateUrl('./myPath/modal.html', function (modal) {
        self.modal = modal;
    }, {
        scope: $scope,
        animation: 'slide-in-up'
    });

    self.$onDestroy = function () {
        self.modal.remove();
    });

    function openModal() {
        self.modal.show();
    };
}
Estus Flask
  • 206,104
  • 70
  • 425
  • 565