javascriptangularjsdomangular-services

Should Angular Services Manipulate the DOM?


So as I understand it, it's poor practice to have a service manipulating the DOM. DOM manipulation should be reserved for directives. I'd like to create something similar to a modal where a service is called to generate a DOM element.

e.i.

function MyController($sope, myModal) {

   // Submit a form
   $scope.submit = function() {
      if (formIsValid) {
         // do stuff
      } else {
         myModal.show({
            templateUrl: 'sometemplate.html',
            controller: 'MyModalController'
         }).then(function() {
            // do stuff
         });
      }
   }

}

Trying to think of different ways to do this and it seems like the simplest way would be to have the service inject a DOM element into the page-

function MyModalService($http, $compile, $controller, $rootScope) {

   this.show = function (options) {
      var $scope = $rootScope.$new(true);
      $controller(options.controller, {
         $scope: $scope
      });

      $http.get(options).success(function(html) {
         var ele = $compile(html)($scope);

         // Bad practice? Alternatives?
         angular.element('body').append(ele);
      });
   }

}

This may seem like small potatoes but I like to stick to a pattern and I like reasons to break pattern or to revise the pattern. Is this common or is there a better way to do this?


Solution

  • This sounds very similar to what angular-bootstrap does for their modal.

    You can check out their implementation here: https://github.com/angular-ui/bootstrap/blob/master/src/modal/modal.js#L452