programing

AngularJS - 디렉티브의 링크 기능에서 격리된 스코프에 액세스합니다.

subpage 2023. 4. 4. 21:18
반응형

AngularJS - 디렉티브의 링크 기능에서 격리된 스코프에 액세스합니다.

Angular에서 처음 해보는 거야JS 커스텀 디렉티브

디렉티브의 링크 함수에서 격리된 스코프를 사용하는(또는 이해하는) 문제가 있습니다.

다음은 내 앱의 이 부분 코드입니다.

표시. 삭제

...
<raw-data id="request-data" title="XML of the request" data="request">See the request</raw-data>
...

request는 viewCtrl 범위에서 퍼블리시되는 변수이며 요청의 xml 문자열을 포함합니다.

rawData.js

directives.directive('rawData', function() {

    return {
        restrict : 'E',
        templateUrl : 'partials/directives/raw-data.html',
        replace : true,
        transclude : true,
        scope : {
            id : '@',
            title : '@',
            data : '='
        },
        link : function($scope, $elem, $attr) {
            console.log($scope.data); //the data is correclty printed
            console.log($scope.id); //undefined
        }
    };
});

raw-data.displaces

<div>
    <!-- Button to trigger modal -->
    <a href="#{{id}}Modal" role="button" class="btn" data-toggle="modal" ng-transclude></a>

    <!-- Modal -->
    <div id="{{id}}Modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="{{id}}Modal" aria-hidden="true">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h3 id="myModalLabel">{{ title }}</h3>
        </div>
        <div class="modal-body">
            <textarea class="input-block-level" rows="10">{{ data }}</textarea>
        </div>
        <div class="modal-footer">
            <!-- <button class="btn" ng-click="toggleTagText('')">{{'cacher'}} l'image</button> -->
            <button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Fermer</button>
        </div>
    </div>
</div>

모달 팝을 할 때 아이디가 왜 보이는지 이해가 안 되는데console.log()값은 정의되어 있지 않습니다.

격리된 스코프 값이 잘못되었을 수 있습니다(=그리고.@).

읽어주셔서 감사합니다.:)

로 바인드된 스코프 속성을 분리하다@는 링크 기능에서 즉시 사용할 수 없습니다.를 사용해야 합니다.$observe:

$attr.$observe('id', function(value) {
   console.log(value);
});

Angular가 격리된 스코프 속성을 자동으로 업데이트하므로 템플릿이 제대로 작동합니다.id널 위해서.업데이트가 되면 템플릿도 자동으로 업데이트됩니다.

문자열을 전달하기만 하면 값을 한 번만 평가할 수 있습니다.@바인딩:

link: function($scope, $elem, $attr) {
    var id    = $attr.id;
    var title = $attr.title
    console.log(id, title);
}

단, 템플릿의 속성을 사용하려면 다음 명령을 사용해야 합니다.@.

템플릿을 사용하지 않는 경우@Atribute 값에 다음 값이 포함된 경우 유용합니다.{{}}s – 예:title="{{myTitle}}". 그럼 사용할 필요가 있습니다.$observe보다 명확해진다: 링크 함수는, 다음의 값이 될 때마다, 무엇인가 하고 싶은 경우가 있다.myTitle변화들.

이는 의도적인 것으로 컴파일 순서 및 '@'와 '='의 차이와 관련이 있습니다.

Misko가 입력한 Google Groups 토론에서 발췌한 내용:

@와 =는 전혀 다른 일을 한다.하나는 속성 값(보간할 수 있음)을 복사하고 다른 하나는 속성 값을 식(expression)으로 처리합니다.

@attrs는 나중에야 $인정되므로 링크 시 사용할 수 있습니다.링크 함수로 작업을 수행하려면 $interpolate를 수동으로 수행해야 합니다.

위의 답변 중 어느 것도 실제로 하나의 핵심 측면을 언급하지 않았습니다. '='를 사용하더라도 다음과 같이 스코프 내부 링크 기능에 직접 액세스할 수 있는 것 같지는 않습니다.

scope: {
    data: '=',
},
link: function(scope, elem, attrs) {
    console.debug(scope.data); // undefined

내부 기능에서는 스코프에 액세스 할 수 있습니다.

link: function(scope, elem, attrs) {
    scope.saveComment = function() {
        console.debug(scope.data);

따라서 scope.data를 사용할 수 있는 시차가 있을 수 있습니다.

제가 만든 JSFiddle은 http://jsfiddle.net/7t984sf9/5/에서 보실 수 있습니다.

link: function($scope, $elem, $attr) {
    console.log($scope.onewayObject);
    $attr.$observe('onewayObject', function(value) {
         console.log(value);
    });
}

또는 자세한 설명은 다음과 같습니다.& vs @ 및 =의 각도 차이는 무엇입니까?JS

언급URL : https://stackoverflow.com/questions/17111016/angularjs-access-isolated-scope-in-directives-link-function

반응형