programing

Angular 요소의 지시 템플릿 고유 IDJS

madecode 2023. 4. 1. 23:08
반응형

Angular 요소의 지시 템플릿 고유 IDJS

한 페이지에 여러 번 사용할 수 있는 지침이 있습니다.이 지시문 템플릿에서는 다음과 같이 라벨을 "바인드"할 수 있도록 입력 요소에 ID를 사용해야 합니다.

<input type="checkbox" id="item1" /><label for="item1">open</label>

여기서 문제는 지시문이 여러 번 포함되면 ID "item1"이 고유하지 않고 라벨이 제대로 작동하지 않는다는 것입니다(클릭 시 체크박스를 켜거나 꺼야 합니다).

이 문제는 어떻게 해결됩니까?템플릿에 "ctl00" 또는 "ctl00"을 할당하는 방법이 있습니까(asp.net이 ctl00을 사용하는 경우와 같음).프리픽스)또는 Scope의 디렉티브 ID + 스태틱 ID로 구성된 각 id-Attribute에 angular-Expression을 포함해야 합니까?예를 들어 다음과 같습니다.

<input type="checkbox" id="{{directiveID}} + 'item1'" /><label for="{{directiveID}} + 'item1'">open</label>

편집:

마이 디렉티브

module.directive('myDirective', function () {
    return {
        restrict: 'E',
        scope: true, 
        templateUrl: 'partials/_myDirective.html',
        controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
            ...
        } //controller
    };
}]);

내 HTML

<div class="myDirective">
  <input type="checkbox" id="item1" /><label for="item1">open</label>
</div>

HTML

    <div class="myDirective">
        <input type="checkbox" id="myItem_{{$id}}" />
        <label for="myItem_{{$id}}">open myItem_{{$id}}</label>
    </div>

갱신하다

Angular 1.3은 네이티브의 게으른 일회성 바인딩을 도입했습니다.각도 표현 문서:

원타임 바인딩

::로 시작하는 식은 일회성으로 간주됩니다.1회성 표현식은 안정되면 재계산을 중지합니다.식 결과가 정의되지 않은 값일 경우 첫 번째 다이제스트 후에 발생합니다(아래의 값 안정화 알고리즘 참조).

네이티브 솔루션:

.directive('myDirective', function() {

    var uniqueId = 1;
    return {
        restrict: 'E',
        scope: true,
        template: '<input type="checkbox" id="{{::uniqueId}}"/>' +
                  '<label for="{{::uniqueId}}">open</label>',
        link: function(scope, elem, attrs) {
            scope.uniqueId = 'item' + uniqueId++;
        }
    }
})

한 번만 바인딩:

  • 바인딩({}/ng-bind)을 사용하면 안 되는 경우
  • 바인딩은 $watch를 사용하기 때문에 비쌉니다.이 예에서는 $digest마다 angular dirty가 ID의 변경을 체크하지만 설정은 1회뿐입니다.
  • 다음 모듈을 확인합니다.https://github.com/Pasvaz/bindonce

솔루션:

.directive('myDirective', function() {

    var uniqueId = 1;
    return {
        restrict: 'E',
        scope: true,
        template: '<input type="checkbox"/><label>open</label>',
        link: function(scope, elem, attrs) {
            var item = 'item' + uniqueId++;
            elem.find('input').attr('id' , item);
            elem.find('label').attr('for', item);
        }
    }
})

예를 들어 Selenium 테스트에서 id를 사용하기 때문에 BlockId 파라미터를 스코프에 추가합니다.그들이 독특하지 않을 가능성은 아직 있지만, 우리는 그들을 완전히 통제하는 것을 선호합니다.또 하나의 장점은 아이템에 좀 더 알기 쉬운 ID를 부여할 수 있다는 것입니다.

지시 JS

module.directive('myDirective', function () {
    return {
        restrict: 'E',
        scope: {
            blockId: '@'
        }, 
        templateUrl: 'partials/_myDirective.html',
        controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
            ...
        } //controller
    };
}]);

지시 HTML

<div class="myDirective">
  <input type="checkbox" id="{{::blockId}}_item1" /><label for="{{::blockId}}_item1">open</label>
</div>

사용.

<my-directive block-id="descriptiveName"></my-directive>

Ilan과 BuriB의 솔루션(더 일반적이고 좋은 솔루션)을 제외하고 라벨의 "for" 속성에 대한 ID가 필요했기 때문에 특정 문제에 대한 해결책을 찾았습니다.대신 다음 코드를 사용할 수 있습니다.

<label><input type="checkbox"/>open</label>

다음 Stackoverflow-Post가 도움이 되었습니다.

https://stackoverflow.com/a/14729165/1288552

언급URL : https://stackoverflow.com/questions/21021951/directive-template-unique-ids-for-elements-in-angularjs

반응형