Html file as content in Bootstrap popover in AngularJS directive

后端 未结 2 896
感情败类
感情败类 2021-02-01 16:40

I have an Angular directive to handle Bootstrap popovers as shown in the code below. In my directive I\'m setting the popover content to a HTML string, which I think is ugly. W

相关标签:
2条回答
  • 2021-02-01 17:24

    To complete the answer from Khahn, if you load a dynamic template, the last part should look like that:

    return {
    restrict: "A",
    scope: {
        item: "=" // what needs to be passed to the template
    },
    link: function(scope, element, attrs) {
    
      getTemplate("user").then(function(popOverContent) {
    
        var options = {
          content: $compile($(popOverContent))(scope),
          placement: "bottom",
          html: true,
          trigger: "hover"
        };
        $(element).popover(options);
    
      });
    }
    

    };

    0 讨论(0)
  • 2021-02-01 17:31

    A quick solution is using templateCache with inline template:

    Inline template:

    <script type="text/ng-template" id="templateId.html">
          This is the content of the template
    </script>
    

    Js:

    app.directive('mypopover', function ($compile,$templateCache) {
    
        var getTemplate = function (contentType) {
            var template = '';
            switch (contentType) {
                case 'user':
                    template = $templateCache.get("templateId.html");
                    break;
            }
            return template;
        }
    

    DEMO

    If you need to load external templates, you need to use ajax $http to load the templates manually and put in the cache. Then you can use $templateCache.get to retrieve later.

    $templateCache.put('templateId.html', YouContentLoadedUsingHttp);
    

    Sample code:

    var getTemplate = function(contentType) {
        var def = $q.defer();
    
        var template = '';
        switch (contentType) {
          case 'user':
            template = $templateCache.get("templateId.html");
            if (typeof template === "undefined") {
              $http.get("templateId.html")
                .success(function(data) {
                  $templateCache.put("templateId.html", data);
                  def.resolve(data);
                });
            } else {
               def.resolve(template);
            }
            break;
        }
        return def.promise;
      }
    

    DEMO

    0 讨论(0)
提交回复
热议问题