programing

angularjs 지시문에 대해 트랜슬루드 콘텐츠가 제공되었는지 감지합니다.

newnotes 2023. 3. 16. 21:51
반응형

angularjs 지시문에 대해 트랜슬루드 콘텐츠가 제공되었는지 감지합니다.

지시문(프로그레스바)은 설명 없는 상태와 왼쪽에 라벨이 있는 상태의 두 가지입니다.이 라벨은 트랜스코드된 콘텐츠를 간단하게 사용하는 것이 좋습니다.

트랜슬루드 콘텐츠가 제공되었는지 여부에 따라 지시문에 클래스를 추가하는 방법을 아는 사람이 있습니까?

그래서 추가하겠습니다.

<div class="progress" ng-class="{withLabel: *CODE GOES HERE*}">
    <div class="label"><span ng-transclude></span>
    <div class="other">...</div>
</div>

정말 고마워.

Angular v1.5와 멀티 슬롯 트랜슬루전 릴리스 후에는 더욱 심플해졌습니다.예를 들어,component대신directive액세스 할 수 없습니다.link또는compile기능들.그러나 당신은 에 액세스 할 수 있습니다.$transclude서비스.따라서 'official' 방식으로 컨텐츠의 존재 여부를 확인할 수 있습니다.

app.component('myTransclude', {
  transclude: {
    'slot': '?transcludeSlot'
  },
  controller: function ($transclude) {
    this.transcludePresent = function() {
      return $transclude.isSlotFilled('slot');
    };
  }
})

다음과 같은 템플릿을 사용합니다.

<div class="progress" ng-class="{'with-label': withLabel}">
    <div class="label"><span ng-transclude="slot"></span>
    <div class="other">...</div>
</div>

@Ilan의 솔루션을 기반으로 이 간단한 $transclude 함수를 사용하여 트랜스코드된 콘텐츠가 있는지 여부를 확인할 수 있습니다.

$transclude(function(clone){
    if(clone.length){
        scope.hasTranscluded = true;
    }
});

Plnkr은 ng-if를 사용하여 이 접근방식을 시연하고 트랜슬루드가 없는 경우 기본 콘텐츠를 설정합니다.http://plnkr.co/hHr0aoSktqZYKoiFMzE6

여기 plunker가 있습니다.http://plnkr.co/edit/ednJwiceWD5vS0orewKW?p=preview

링크 함수 내에서 트랜스코드된 요소를 찾아 내용을 확인할 수 있습니다.

지시:

app.directive('progressbar', function(){
  return {
    scope: {},
    transclude: true,
    templateUrl: "progressbar.html",
    link: function(scope,elm){
      var transcluded = elm.find('span').contents();
      scope.withLabel = transcluded.length > 0; // true or false
    }
  }
})

템플릿:

<div class="progress" ng-class="{'with-label': withLabel}">
    <div class="label"><span ng-transclude></span>
    <div class="other">...</div>
</div>

다음과 같이 사용자 정의 변환 지시문을 작성할 수도 있습니다.

app.directive('myTransclude', function(){

  return {
    link: function(scope, elm, attrs, ctrl, $transclude){
      $transclude(function(clone){

        // Do something with this:
        // if(clone.length > 0) ...

        elm.empty();
        elm.append(clone);
      })
    }
  }
})

@plong0 & @Ilan의 솔루션에서는 공백 공간에서도 동작하기 때문에 조금 더 효과가 있는 것 같습니다.

$transcludeFn(function(clonedElement) {
    scope.hasTranscludedContent = clonedElement.html().trim() === "";
});

이전에 있었던 곳<my-directive> </my-directive>를 가지고 있는 것을 되돌리고 싶다.length1텍스트 노드가 포함되어 있기 때문입니다.함수가 넘어간 이래$transcludeFn변환된 콘텐츠 내용의 jQuery 개체를 반환합니다. 내부 텍스트를 가져오고 끝의 공백을 제거한 후 공백 여부를 확인할 수 있습니다.

텍스트만 확인하므로 텍스트가 없는 html 요소를 포함해도 공백으로 플래그가 지정됩니다.다음과 같이 합니다.<my-directive> <span> </span> </my-directive>- 그래도 제 욕구에 잘 맞았습니다.

언급URL : https://stackoverflow.com/questions/21547781/detect-if-a-transclude-content-has-been-given-for-a-angularjs-directive

반응형