简体   繁体   中英

Angular directive access template elements from controller

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
   }

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM