简体   繁体   English

来自控制器的Angular指令访问模板元素

[英]Angular directive access template elements from controller

I'm using an angular directive to add a reusable popup to various elements. 我正在使用angular指令将可重用的弹出窗口添加到各种元素。 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. 当您想通过将模式弹出窗口附加到文档主体来显示模式弹出窗口时,您正在操纵DOM。 There is one place where DOM manipulation is Ok, and that's the directive's link function. 在一个地方可以进行DOM操作就可以了,那就是指令的链接功能。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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