Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ui modal with controller in separate js file

I am trying to make a modal which can be instantiated from multiple places in the app. from the example given here: Angular directives for Bootstrap the modal controller is in the same file as the controller who instantiates the modal. I want to separate the modal controller from the "app" controller.

index.html:

<!DOCTYPE html>
<html ng-app="modalTest">

  <head>
    <link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  </head>

  <body ng-controller="modalTestCtrl">
    <button ng-click="openModal()">Modal</button>

    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap.min.js"></script>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.min.js"></script>
    <script type="text/javascript" src="modalTest.js"></script>
  </body>

</html>

The controller:

var app = angular.module('modalTest', ['ui.bootstrap']);

app.controller('modalTestCtrl', ['$scope', '$modal', function($scope, $modal) {
    $scope.openModal = function() {
        var modalInstance = $modal.open({
            templateUrl: 'modal.html',
            controller: 'modalCtrl',
            size: 'sm'

        });
    }
 }]);
// I want this in another JavaScript file... 
app.controller('modalCtrl', ['$scope', function($scope) {
    $scope.hello = 'Works';
}]);

modal.html:

<div ng-controller="modalCtrl">
    <div class="modal-header">
        <h3 class="modal-title">I'm a modal!</h3>
    </div>
    <div class="modal-body">
        <h1>{{hello}}</h1>
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary" ng-click="ok()">OK</button>
        <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
    </div>
</div>

Is there any way to put the modalCtrl in another JavaScript file and somehow inject the controller (modalCtrl) into the modalTestCtrl ?

BR

like image 949
user3594184 Avatar asked Aug 31 '14 22:08

user3594184


1 Answers

Of course, you can do it. First of all you should use a function declaration.

// modalCtrl.js
// This file has to load before modalTestCtrl controller
function modalCtrl ($scope) {
   $scope.hello = 'Works';
};

Then, change the modalTestCtrl like:

app.controller('modalTestCtrl', ['$scope', '$modal', function($scope, $modal) {
$scope.openModal = function() {
    var modalInstance = $modal.open({
        templateUrl: 'modal.html',
        controller: modalCtrl, //This must be a referance, not a string
        size: 'sm'

    });
}
}]);

With the changes above, you code has to work.

like image 86
turhanco Avatar answered Sep 30 '22 19:09

turhanco