Angular UI Modal, built-in template and controller

I want to create a really simple confirmation window using the UI modal code, which I have successfully used to create complex modals that in the past loaded their template and controller from external files.

It is so simple, although I do not want to rely on external template and controller files, just a box with a close button, which is somehow connected to the controller declared directly in the modal instance.

Here is what I tried unsuccessfully ...

var modalInstance = $modal.open({ template: "<div>Message goes here...<button ng-click='cancel()'>Continue</button></div>", controller: function(){ $scope.cancel = function(){ alert("Cancelled"); }; } }); 
+8
javascript angularjs angular-ui
source share
3 answers

It looks like you need to inject $ scope into your controller function

controller: function($scope){

The modal template size does not match the area in the controller in which you defined the modal instance.

The reason you don't get undefined errors: $ scope is a closure variable, so adding .cancel () to it works fine. But, since this is not the same area of ​​modality, therefore ng-click does not see .cancel () in its area.

I reproduced in this jsbin: http://jsbin.com/gejuxije/1/edit

Edit: Since you mentioned that you do not need external files for the template, here is a demonstration of how to define a template for the modal inside the presentation template on which it is used.

http://jsbin.com/gejuxije/2/edit

You can put html inside the inline script ...

 <script type="text/ng-template" id="myModalTemplateName.html"></script> 
+7
source share

The value you pass to the "template" should be valid HTML and ideally should contain the appropriate CSS modal classes.

You may also need to transfer the scope of the controller.

 var modalInstance = $modal.open({ scope:$scope, template: "<div>Message goes here...<button ng-click='cancel()'>Continue</button></div>", controller: function(){ $scope.cancel = function(){ alert("Cancelled"); }; } }); 

In general, I did not have to do this, but since you define the controller in an open method, this may be necessary. According to the docs, he should create a new area as a child of rootScope, but I suspect that your mileage is changing. I would like the instructions on the website to be a little more informative on this topic.

You can also try $ close and $ clean. I have never tried them, but since you are out of luck with a variable scope, this may be what you need.

+2
source share

I'm just trying to do something like this and stumbled upon this. I know this old, but it can help someone.

Simply put

 modalInstance.close(); 

in cancel function

+1
source share

All Articles