unibax99 unibax99 - 3 months ago 22
AngularJS Question

ng-click doesn't invoke function in md-dialog

I have problem with ng-click in md-dialog.
Here is my HTML code

dialog.html

<md-dialog-content layout="column">
<div class="md-dialog-content">
<md-input-container>
<label>Title</label>
<input ng-model="vm.newMovie.title"/>
</md-input-container>
<md-input-container>
<label>Year</label>
<input ng-model="vm.newMovie.year"/>
</md-input-container>
<md-input-container>
<label>ID</label>
<input ng-model="vm.newMovie.id"/>
</md-input-container>
<md-button class="md-raised" ng-click="vm.test()">HEHEHE</md-button>
<md-dialog-actions>
<md-button ng-click="vm.addMovie()" class="md-raised md-primary">Add Movie</md-button>
</md-dialog-actions>
</div>
</md-dialog-content>


dialog.controller.js

(function() {
'use strict';

angular
.module('app.movies')
.controller('DialogController', DialogController);

/** @ngInject */
function DialogController($http) {
var vm = this;

vm.newMovie = {};

function trolo() {
console.log('dasa');
}

vm.test = function() {
console.log('test test');
}

vm.addMovie = function() {
console.log(vm.newMovie);
$http.post('http://192.168.0.12:3000/movies/' + vm.newMovie.title + '/' + vm.newMovie.year + "/" + vm.newMovie.id).then(function(response) {
console.log(vm.newMovie.title);
});
}
}
})();


movie.controller.js

function() {
'use strict';

angular
.module('app.movies')
.controller('MoviesController', MoviesController);

/** @ngInject */
function MoviesController($http, $mdDialog, toastr) {
var vm = this;
vm.showDialog = function($event) {
$mdDialog
.show({
clickOutsideToClose: true,
escapeToClose: true,
targetEvent: $event,
controller: 'DialogController',
templateUrl: 'app/main/movies/dialogAddMovie.html'
})
.finally(function() {
alert = undefined;
});
}
}
})();


Function showDialog works fine, but the method applied to ng-click is never invoked. Please help. Thanks

Answer

You missed to define controllerAs(alias of your controller) property in your $mdDialog.show method object. As you already supposed vm (controller alias) is defined.

Code

vm.showDialog = function($event) {
  $mdDialog
    .show({
      clickOutsideToClose: true,
      escapeToClose: true,
      targetEvent: $event,
      controller: 'DialogController',
      templateUrl: 'app/main/movies/dialogAddMovie.html',
      controllerAs: 'vm' //<--- provide an alias to `DialogController` before using it.
    })
    .finally(function() {
      alert = undefined;
    });
}
Comments