1
\$\begingroup\$

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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 7, 2013 at 8:03
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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.

answered Dec 10, 2013 at 1:08
\$\endgroup\$
1
  • \$\begingroup\$ here is a simple example of modal that uses approach described by Kenneth \$\endgroup\$ Commented Dec 22, 2014 at 3:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.