I am using ionicframework together with TypeScript. When I create a modal object as seen below, the modal object is created successfully but inside the callback where it says this.$scope.modal = modal; this is referencing the browser window and hence the $scope is undefined. How can I get this to point to the class?
export class MyCtrl {
constructor(private $scope: any, private $ionicModal) {
// Load the modal from the given template URL
this.$ionicModal.fromTemplateUrl('MyApp/myModal.html', (modal) => {
this.$scope.modal = modal;
}, {
// Use our scope for the scope of the modal to keep it simple
scope: this.$scope,
// The animation we want to use for the modal entrance
animation: 'slide-in-up'
});
In TypeScript, the this
inside a lambda doesn't have the traditional behavior of this
in JavaScript. If you look at the compiled JS it will be clear what's happening, but basically it will usually be a level higher than you'd expect - in your case the window object.
The easiest way to work around this is to do a var self=this;
above the line with the comment and then reference self
in your lambda, or else just use normal function syntax such as function(modal) {
which preserves the traditional functionality of this
from JS.
Dan Quirk answered a similar question that I had here: https://typescript.codeplex.com/workitem/1655
You may also wish to take a look at this: Can I access the other this in a TypeScript lambda?
If you call something like new MyCtrl($myScope, $ionicModal)
, references to this
will correctly point to the new instance of MyCtrl
.
What I suspect is that you're passing the MyCtrl
class into a place where Angular expects a function, not a class!
Your code actually fails unhelpfully late due to a confusing aspect of JavaScript, namely that constructors can be (mis)used as normal functions without using new
, in which case this
will point to something higher up.
The solution is to use a normal function instead of a class, try:
function myCtrl($scope: any, $ionicModal) {
// Load the modal from the given template URL
$ionicModal.fromTemplateUrl('MyApp/myModal.html', (modal) => {
$scope.modal = modal;
}, {
// Use our scope for the scope of the modal to keep it simple
scope: $scope,
// The animation we want to use for the modal entrance
animation: 'slide-in-up'
});