# Creating dialogs and modals with AngularJS

I wonder whether or not I should improve my current practice on creating/calling dialogs with AngularJS.

Think of a simple information, displayed on demand as a modal window. To create such a thing, I would write a directive, include it to my page and use ng-hide to hide it.

If I want to call it, I would simply change the associated ng-hide value to false from within my main controller.

app.directive('modal',function(){
return{
restrict: 'E',
template: '<div ng-hide=state.modalVisibility></div>',
// etc
}
});

app.controller('Ctrl',function($scope){$scope.state.modalVisibility = false;

$scope.changeVisibility = function(){$scope.state.modalVisibility = true;
}
});


Are there any disadvantages or possible improvements on this practice? Is it a bad idea to have the modal-element "always there" but only displayed on demand?

## 1 Answer

The disadvantage is the modal directive hanging around for no good reason in the templates, and a tight coupling between the controller and the modal directive.

Far better is using a service to inject this modal into the DOM as needed. This is the approach that for example the AngularUI team uses in their approach.

This ensures lower coupling (more creative freedom and less technical debt), more easily testable code, and a more intuitive API. Simply inject and call a service, rather than having to make sure the directive is added, and the controller writes to the correct variable, and they share the same scope etc.

The reason you are encouraged to use directives for DOM manipulation is first and foremost convention and testability issues. Using a service in this use-case is an acceptable exception.

• here is a simple example of modal that uses approach described by Kenneth
– SET
Dec 22, 2014 at 3:01