programing

Angular의 부트스트랩 팝오버 콘텐츠로서의 Html 파일JS 지시어

newnotes 2023. 3. 21. 22:33
반응형

Angular의 부트스트랩 팝오버 콘텐츠로서의 Html 파일JS 지시어

아래 코드와 같이 Bootstrap popover를 처리하는 Angular 지시가 있습니다.제 지시문에서는 팝오버 콘텐츠를 HTML 문자열로 설정하고 있는데, 이 문자열은 보기 흉하다고 생각합니다.HTML 문자열 대신 "template.html" 파일을 사용하고 싶습니다.이렇게 하면 표시하는 팝오버의 종류에 따라 템플릿 파일이 다른 동일한 디렉티브를 사용할 수 있습니다.어쨌든 그게 내 계획이야.

그럼 어떻게 하면 가장 좋은 방법으로 template.html에서 HTML 코드를 로드하여 아래 AngularJs 지시의 HTML 문자열 대신 사용할 수 있을까요?

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

데모

외부 템플릿을 로드해야 할 경우 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;
  }

데모

Khan에서 답변을 완료하려면 동적 템플릿을 로드하는 경우 마지막 부분은 다음과 같습니다.

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

  });
}

};

언급URL : https://stackoverflow.com/questions/21362712/html-file-as-content-in-bootstrap-popover-in-angularjs-directive

반응형