I'm using angular-ui-bootstrap-bower#0.7.0 with angular#1.2.10 and when opening a modal where the controller is an "old fashioned" one, everything works fine.
However, when I have a controller meant to use with the new "controller as syntax" it doesn't work. Does angular-ui-bootstrap modal work with controller as syntax? Does version 0.7 support it? How to do it?
You can use the ngController syntax for the "controller" option.
For example:
controller: 'modalController as modal'
There is a sample plunker
Code from plunker:
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap-css@3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<script data-require="angular.js@1.2.16" data-semver="1.2.16" src="https://code.angularjs.org/1.2.16/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.11.0/ui-bootstrap-tpls.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="demoController as demo">
<h1>{{ demo.message }}</h1>
<button class="btn btn-primary" ng-click="demo.modal()">Open modal</button>
<script type="text/ng-template" id="modal.html">
<div class="modal-header">
<h3 class="modal-title">Modal window</h3>
</div>
<div class="modal-body">
<pre>{{ modal.modalText }}</pre>
</div>
<div class="modal-footer">
<button class="btn btn-default" ng-click="modal.cancel()">Cancel</button>
</div>
</script>
</body>
</html>
script.js
angular.module('app', ['ui.bootstrap'])
.controller('demoController', function($modal) {
this.message = 'It works!'
this.modal = function() {
$modal.open({
controller: 'modalController as modal',
templateUrl: 'modal.html'
});
};
})
.controller('modalController', function($modalInstance) {
this.modalText = 'Modal Text'
this.cancel = function() {
$modalInstance.dismiss();
}
})
In case you are using CoffeeScript, don't forget to explicitly return
the controller function.
Otherwise, the last line will be returned and you will end up with a not working controller as
syntax, and incidentally, on this SO page.
Set 'controllerAs'
property in $uibModal.open()
var modalInstance = $uibModal.open({
animation:true,
templateUrl: '_myModal.html',
controller:['$scope' function($scope){
var mdCtrl=this;
mdCtrl.title="hello world";
}],
controllerAs:'mdCtrl', //set your custom controllerAs name
backdrop: 'static',
size: 'lg',
resolve: {
}
});
modalInstance.result.then(function (selectedItem) {
}, function () {
});
in your template
<h2> {{mdCtrl.title}}</h2>