Skip to content Skip to sidebar Skip to footer

Html File As Content In Bootstrap Popover In Angularjs Directive

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

Solution 1:

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

Solution 2:

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);

  });
}

};

Post a Comment for "Html File As Content In Bootstrap Popover In Angularjs Directive"