alessandro ferrucci alessandro ferrucci - 4 months ago 64
AngularJS Question

angular bootstrap modal controllerAs doesn't work

I have an angular app that shows a modal dialog and I cannot get the controllerAs functionality to work. Here is my app definition:

var deps = ['ngResource', 'ngRoute', 'swaggerUi', 'http-auth-interceptor', 'ngAnimate', 'angular-spinkit', 'ui.bootstrap'];
var myapp = angular.module('myApp', deps);


Here is my controller that invokes the modal and the controller bound to the modal

myapp.controller('UsersController', ['$scope', '$log', '$uibModal', 'UsersService', function ($scope, $log, $uibModal, UsersService) {
$scope.users = UsersService.getAll();
$scope.openAddUserModal = function () {
$uibModal.open({
animation: false,
templateUrl: 'partials/addUserModal.html',
/* I've even tried controller:'AddUserModalCtrl as addUserModalCtrl' */
controller: 'AddUserModalCtrl',
controllerAs: 'addUserModalCtrl',
bindToController: true
});
};
}]).controller('AddUserModalCtrl', ['$scope', '$log', '$uibModalInstance', function ($scope, $log, $uibModalInstance) {
$scope.cancel = function () {
console.log('userToAdd: ' + JSON.stringify($scope.userToAdd));
$uibModalInstance.dismiss('cancel');
};
$scope.addUser = function () {
console.log($scope.username);
}
}])


And here is the modal html:

<div class="modal-header">
<h3 class="modal-title">Add new user</h3>
</div>
<div class="modal-body">
<form role="form">
<button ng-click="addUser()" type="submit" class="btn btn-default">Submit</button>
<!-- this works if I remove the 'addUserModalCtrl' -->
<button ng-click="addUserModalCtrl.cancel()" type="submit" class="btn btn-default">Cancel</button>
</form>
</div>

Lex Lex
Answer

It's because you are adding the methods to $scope. You don't do that when using controllerAs syntax. You should use this. notation for your functions in AddUserModalCtrl.

this.cancel = function () {
    console.log('userToAdd: ' + JSON.stringify(this.userToAdd));
    $uibModalInstance.dismiss('cancel');
};
this.addUser = function () {
    console.log(this.username);
}