Angular ui modal with controller in separate js file

I am trying to create a modal that can be created from several places in an application. from the example here: Angular directives for Bootstrap , the modal controller is in the same file as the controller that creates the modality instance. 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> 

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 a way to put modalCtrl in another JavaScript file and somehow introduce a controller (modalCtrl) into modalTestCtrl?

BR

+6
source share
1 answer

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

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

Then change modalTestCtrl as:

 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 above changes, the code should work.

+9
source

Source: https://habr.com/ru/post/974626/


All Articles