alessandro ferrucci alessandro ferrucci - 1 year ago 168
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 () {
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));
$scope.addUser = function () {

And here is the modal html:

<div class="modal-header">
<h3 class="modal-title">Add new user</h3>
<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>

Lex Lex
Answer Source

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));
this.addUser = function () {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download