Html file as content in Bootstrap popover in AngularJS directive

后端 未结 2 902
感情败类
感情败类 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:31

    A quick solution is using templateCache with inline template:

    Inline template:

    
    

    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

提交回复
热议问题