1

I'm using an angular directive to add a reusable popup to various elements. Due to styling constraints, rather than adding the popover to the element, I need to add it to the document body. I would later like to access it in my controller - how would I go about doing so?

.controller 'slUserCtrl', ($element) ->
   $element.popup
      hoverable: true
      position: 'bottom right'
      popup: # What do I put here to get the "template" DOM element?

.directive 'slUser', ($document) ->
   template = $templateCache.get 'users/sl-user.html'

   return {
      restrict: "A"
      controller: 'slUserCtrl'
      compile: (elem, attrs) ->
         angular.element(document.body).append template
   }

1 Answer 1

1

When you want to display a modal popup by attaching it to the document body, you are manipulating the DOM. There is one place where DOM manipulation is Ok, and that's the directive's link function.

var app = angular.module('app',[]);
app.controller('ctrl', function($scope) {
});

app.directive('modal', function() {
  return {
    restrict: 'A',
    transclude: 'element',    
    controller: function($rootScope) {
      $rootScope.dialog = { show: false };
    },
    link: function(scope, element,attr,ctrl, transclude) {      
      transclude(function(clone, scope) {
        scope.$watch('dialog.show', function (val) {
          if (val) {
            clone.css('display', 'block');  
          }
          else {


            clone.css('display', 'none');                
          }
        });
        angular.element(document.body).append(clone);
      });
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app">
  
  <div ng-controller="ctrl">
    Hello World!
    <button ng-click="dialog.show = !dialog.show">Open Modal </button> {{test}}
    <div modal>
         This is a modal dialog
    </div>
  </div>
  
</body>

Sign up to request clarification or add additional context in comments.

1 Comment

The problem is that I have many of these popups attached to an element with ng-repeat. Is there a way to solve this without rootscope?

Your Answer

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.