Html 文件作为 AngularJS 指令中 Bootstrap 弹出窗口中的内容

2023-12-29

我有一个 Angular 指令来处理 Bootstrap 弹出窗口,如下面的代码所示。在我的指令中,我将弹出窗口内容设置为 HTML 字符串,我认为这很难看。 我想要做的是使用“template.html”文件而不是 HTMLstring。这样,我将能够根据我想要显示的弹出窗口类型,对不同的模板文件使用相同的指令。无论如何,这就是我的计划。

那么,如何以最佳方式从 template.html 加载 html 代码并使用它而不是下面 AngularJs 指令中的 HTMLstring 呢?

app.directive('mypopover', function ($compile) {

var HTMLstring = "<div><label class='control-label' style='color: rgb(153, 153,153)'>Search</label>&nbsp;&nbsp;"+"<input placeholder='Search assignment' ng-model='searchText' type='text' class='form-control'> <br>"+"<label class='control-label' style='color: rgb(153, 153, 153)'>Select an assignable</label>"+"<p ng-repeat='p in projects | filter:searchText'ng-click='createEvent(user.id,date)'>"+"{{p.title}}</p></div>";

var getTemplate = function (contentType) {
    var template = '';
    switch (contentType) {
        case 'user':
            template = HTMLstring;
            break;
    }
    return template;
}
return {
    restrict: "A",
    link: function (scope, element, attrs) {
        var popOverContent;
        if (scope.user) {
            var html = getTemplate("user");
            popOverContent = $compile(html)(scope);                    
        }
        var options = {
            content: popOverContent,
            placement: "right",
            html: true,
            date: scope.date
        };
        $(element).popover(options);
    },
    scope: {
        user: '=',
        date: '='
    }
};
});

一个快速的解决方案是使用 templateCache 和内联模板:

内联模板:

<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 http://plnkr.co/edit/qoTcdEAA5o0PgQ7IwJLb?p=preview

如果需要加载外部模板,则需要使用ajax $http手动加载模板并放入缓存中。然后你可以使用$templateCache.get以便稍后检索。

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

示例代码:

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 http://plnkr.co/edit/WljWO6RVGIWRTvCN8KO9?p=preview

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Html 文件作为 AngularJS 指令中 Bootstrap 弹出窗口中的内容 的相关文章

随机推荐