Nice programing

AngularJS의 요소에 대한 지시문 템플릿 고유 ID

nicepro 2020. 11. 10. 22:16
반응형

AngularJS의 요소에 대한 지시문 템플릿 고유 ID


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

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

이제 문제는 내 지시문이 여러 번 포함 되 자마자 ID "item1"이 더 이상 고유하지 않고 레이블이 올바르게 작동하지 않는다는 것입니다 (클릭하면 확인란을 선택 / 선택 취소해야 함).

이 문제는 어떻게 해결됩니까? 템플릿에 "네임 스페이스"또는 "접두사"를 할당하는 방법이 있습니까 (예 : asp.net이 ctl00 ...- 접두사와 함께 수행함)? 또는 범위의 지시문 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은 네이티브 lazy 일회성 바인딩을 도입했습니다. 로부터 각 표현 문서 :

일회성 바인딩

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

네이티브 솔루션 :

.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의 변경 사항을 확인하지만 한 번만 설정합니다.
  • 이 모듈을 확인하십시오 : 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);
        }
    }
})

We add a BlockId parameter to the scope, because we use the id in our Selenium tests for example. There is still a chance of them not being unique, but we prefer to have complete control over them. Another advantage is that we can give the item a more descriptive id.

Directive JS

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

Directive HTML

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

Usage

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

Apart from Ilan and BuriB's solutions (which are more generic, which is good) I found a solution to my specific problem because I needed IDs for the "for" Attribute of the label. Instead the following code can be used:

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

The following Stackoverflow-Post has helped:

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

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

반응형