Hacker Hacker - 4 months ago 22
AngularJS Question

Close modal from controller not working

I have a directive like below

'use strict';
angular.module('abc.directives', [])
.directive('modal', function () {
return {
template: '<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
'<h4 class="modal-title">{{ modalTitle }}</h4>' +
'</div>' +
'<div class="modal-body" ng-transclude></div>' +
'</div>' +
'</div>' +
'</div>',
restrict: 'E',
transclude: true,
replace:true,
scope:true,
link: function postLink(scope, element, attrs) {
scope.modalTitle = attrs.title;

scope.$watch(attrs.visible, function(value){
if(value == true)
$(element).modal('show');
else
$(element).modal('hide');
});

$(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});

$(element).on('hidden.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
}
};
});


I have a form like

<modal title="Error" id='successmessage' visible="successmessage">
<form role="form">
Action was uccesful
<span class="clearfix"></span>
<button type="submit" class="btn btn-primary" ng-click="closemodal('successmessage');>Ok</button>
</form>
</modal>
<modal title="Error" id='errormessage' visible="errormessage">
<form role="form">
Action was not Succesful
<span class="clearfix"></span>
<button type="submit" class="btn btn-primary" ng-click="closemodal('errormessage');>Ok</button>
</form>




I am trying to close the modal when i click on closemodal like

$scope.closemodal = function(scopename)
{
$scope[scopename] = false;
}


i am trying to close the model by setting the property to false. but it does not work. How do i fix it?

ccg ccg
Answer

Is this what you are looking for:

angular.module('my-app', [])
.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" ng-click="closemodal()">&times;</button>' + 
                '<h4 class="modal-title">{{ modalTitle }}</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      link: function postLink(scope, element, attrs) {
        scope.modalTitle = attrs.title;
        scope.showModal = true;

        scope.closemodal = function () {
          scope.showModal = false;
        };
      }
    };  
  });

Working example here: http://codepen.io/cgav/pen/bVNEYz?editors=101

Comments