Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

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.

share|improve this answer
    
here is a simple example of modal that uses approach described by Kenneth –  SET Dec 22 '14 at 3:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.