spez86 spez86 - 1 month ago 11
AngularJS Question

Using ‘this’ as scope when creating $ionicModal

I seem to be having an issue creating an

$ionicModal
when trying to specify my scope as
this
instead of
$scope
.

Since I'm binding everything in my controller via an instance name, I'm not using
$scope
inside of the controller.

So, I initiate the modal as instructed here in Ionic Framework doc
and switched
$scope
with
this


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


When the app runs, I get the following error:


undefined is not a function


and it references the following code in ionic.bundle.js:

var createModal = function(templateString, options) {
// Create a new scope for the modal
var scope = options.scope && options.scope.$new() || $rootScope.$new(true);


I even tried assigning another variable to represent
this
and running it that way, but the same error prevails!

If I'm not using
$scope
in my controller, what would be the best way to load a modal while maintaining the usage of
this
? Is it just not possible or am I missing something?

EDIT-
As requested, adding more info to the original,

Template:

<div id="wrapper" ng-controller="MainCtrl as ctrl">
<button ng-click="ctrl.demo()">Demo Button</button>
</div>


Controller:

angular.module('MyDemo', ['ionic'])
.controller('MainCtrl', function ($ionicModal) {
var _this = this;
this.demo = function () {
//do demo related stuff here
}

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


So, basically, I'm using the 1st declaration style found here:
https://docs.angularjs.org/api/ng/directive/ngController

EDIT: Changed
this
to
_this
inside of
$ionicModal


As requested, here's a plunker with the code above:
http://plnkr.co/edit/4GbulCDgoj4iZtmAg6v3?p=info

Answer

Because of how AngularJs currently sets up the controller when using the "controller as" syntax, you only have whatever functions and properties that you yourself define in the controller function. In order to access the $new() function that AngularJs provides to create child scopes, you need to provide an AngularJs $scope object -- which you can still get by getting it injected into your constructor function, even when using the "controller as" syntax.

angular.module('MyDemo', ['ionic'])
.controller('MainCtrl', function ($scope, $ionicModal) {
  var _this = this;
  this.demo = function () {
    //do demo related stuff here
  }

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