How to use Ionic Popup with scope in Controller As syntax?

6k Views Asked by At

I have an Angular controller setup using Controller as syntax and I need to create an Ionic Popup with a bound data field from one the methods. What I can't figure out is how to set the scope of the popup for the data-binding. I found this example but it seems really messy to me to use both this and $scope. Is there a better way to do this or should I just go back to the $scope method?

My controller looks like this (with questions marked):

.controller('AccountCtrl', function ($ionicPopup) {
    // Properties ===========
    this.resetData = {};

    // Methods ==============
    this.forgotPassword = function () {
        var myPopup = $ionicPopup.show({
            template: '<input type="text" ng-model="<What goes here?>.resetData.resetEmail">',
            title: 'Please enter your e-mail address',
            scope: <What goes here?>
            buttons: [
                {
                    text: 'Submit',
                    onTap: function (e) {
                        console.log("Password reset:" + <What goes here?>.resetData);
                    }
                },
                { text: 'Cancel' }
            ]
        });
    }
})

And my template looks like:

<ion-view view-title="Sign In">
    <ion-content has-bouncing="false" ng-controller="AccountCtrl as account">
        <a href="#" ng-click="account.forgotPassword()">Forgot your password?</a>
    </ion-content>
</ion-view>

Any thoughts would be appreciated. Thanks, Jason

1

There are 1 best solutions below

6
On BEST ANSWER

In that example they inject $scope so they can assign it as the scope property in the popup show options.

Maybe if I clear up what the "controller as" syntax is actually doing, you won't feel like it's so messy :)

When you do ng-controller="myController as ctrl", all you're doing is declaring a variable called ctrl on the $scope for that controller and setting it's value to the this for that controller. Doing "myController as ctrl" is literally exactly the same as doing it without the "as" shortcut like this:

<!-- markup -->
<div ng-controller="myController"></div>

Then in your controller:

// controller
app.controller('myController', function ($scope) {
  $scope.ctrl = this;
});

The only difference when you do "myController as ctrl" is that $scope.ctrl = this just happens for you behind the scenes.

Check out this demo for proof that they are one and the same.

What they are doing in the demo you linked appears to be totally fine in my opinion ;)

Here's a blog post I wrote about "controller as" if you're interested: http://codetunnel.io/angularjs-controller-as-or-scope/