【问题标题】:How to call a directive inside a service in template attribute in AngularJS?如何在AngularJS的模板属性中调用服务内的指令?
【发布时间】:2015-11-15 01:14:07
【问题描述】:

下面是指令代码和服务代码。如何在服务内部调用指令以及如何调用动态模板

指令代码

angular.module('TestModule').directive('mymodalwindow', function () {
    return {        
        restrict: 'E',       

        template: '<div class="modal-header">' +
    '<h3>{{modalOptions.headerText}}</h3>' +
'</div>' +       
    };
});

服务代码

angular.module('TestModule').service('modalService', ['$modal',
    function ($modal) {
        var modalDefaults = {
            backdrop: true,
            keyboard: true,
            modalFade: true,
            template://How to call the above define directive here?? 1 way is <mymodalwindow></mymodalwindow> But how to pass the directives instead of giving fixed directive name

        };}
        ]);

【问题讨论】:

  • 为什么需要从服务中调用指令?您可以将服务注入指令但不能将指令注入服务
  • 我需要从控制器方法中调用modalService,它会弹出对话框模态。并且需要将服务的模板替换为其他模板。
  • 将服务注入控制器。看看如何:stackoverflow.com/questions/16876748/…

标签: javascript angularjs angularjs-directive angularjs-service


【解决方案1】:

我的情况完全相同——需要一个模态对话服务,并且希望以一种比将服务注入 DOM 更 Angular 的方式来实现。

我能找到的最佳方法是让模态服务创建自己的控制器,如 this post 中所述。

【讨论】:

    【解决方案2】:

    将模板放在指令之外:

    angular.module('TestModule').directive('mymodalwindow', function () {
        return { 
            restrict: 'E',
            templateURL: 'app/template/myTemplate.html'
        };
    });
    

    我的模板.html:

    <div class="modal-header">
        <h3>{{modalOptions.headerText}}</h3>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 2019-03-21
      • 1970-01-01
      • 2014-08-14
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多