javascript - Angular 指令从 Controller 访问模板元素

标签 javascript angularjs coffeescript

我正在使用 Angular Directive(指令)向各种元素添加可重用的弹出窗口。由于样式限制,我需要将其添加到文档正文中,而不是将弹出窗口添加到元素中。我稍后想在我的 Controller 中访问它 - 我将如何执行此操作?

.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
   }

最佳答案

当您想要通过将模式弹出窗口附加到文档正文来显示模式弹出窗口时,您正在操作 DOM。有一个地方可以进行 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>

关于javascript - Angular 指令从 Controller 访问模板元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33538417/

相关文章:

javascript - HTML 表单回发并下载文件时显示进度掩码

javascript - 调整div大小时无法让谷歌地图高度自动调整大小

javascript - ng-repeat 在 Angular.js 中生成额外的 td

javascript - 为什么我的 div 表现得像我指定了一个半厘米的上边距/下边距?

javascript - 禁用当前方法上的实时事件

coffeescript - 如何在 Coffeescript 中使用 Javascript 的 for (attr in this)

javascript for循环只上传一个文件

javascript - 导航栏中的下拉菜单不会展开( Bootstrap 、 Angular 、指令、路线)

javascript - 在 angularjs 中显示聚合列表

javascript - 有效地听 JS .scroll()