Search code examples
angular-uiangular-ui-bootstrap

angular-ui modal with controller as syntax


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?


Solution

  • 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="[email protected]" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
        <script data-require="[email protected]" 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();
      }
    })