Maria Jane Maria Jane - 2 months ago 10
AngularJS Question

using 'this' instead of $scope failed in angularjs

I used megaboiletplate.com for scalfoding my project. I downloaded a starter pack but I'm facing some issue. I've put the starter code to a repo

in this file, line 16 is not triggered when I click the login button. The login button has the view like this

<form ng-submit="login()">
<legend>Log In</legend>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Email" class="form-control" ng-model="user.email" autofocus>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="Password" class="form-control" ng-model="user.password">
</div>
<div class="form-group"><a href="/forgot"><strong>Forgot your password?</strong></a></div>
<button type="submit" class="btn btn-success">Log in</button>
</form>


What's wrong??

Answer

make sure that your code is using the 'controller as' syntax. You can use this in the controller but you must redefine the controller in the HTML. like:

<body ng-controller="mycontroller as ctrl">

then you can use the controller functions like

<form ng-submit="ctrl.login()">

https://docs.angularjs.org/api/ng/directive/ngController

you may have to edit your routing if your controller is assigned there.

.when('/login', {
        templateUrl: 'partials/login.html',
        controller: 'LoginCtrl',
        resolve: { skipIfAuthenticated: skipIfAuthenticated }
      })

would be changed to:

.when('/login', {
        templateUrl: 'partials/login.html',
        controller: 'LoginCtrl',
        controllerAs: 'ctrl',
        resolve: { skipIfAuthenticated: skipIfAuthenticated }
      })

in your case this should be found in the app.js of the boilerplate

Comments