programing

범위 $id로 DOM 요소 가져오기

starjava 2023. 3. 3. 16:46
반응형

범위 $id로 DOM 요소 가져오기

스코프를 요소별로 취득할 수 있습니다.

scope = angular.element($0).scope();
scope.$id; // "003"

되돌리려면 어떻게 해야 하나요?스코프를 사용하여 DOM 요소 찾기$id,예를 들어003?

디버깅을 위해 이 작업을 수행하려고 합니다.스코프 트리에 뭔가 표시되어 있는데 어디서 왔는지 확인하고 싶습니다.

그다지 섹시하지는 않지만 각 돔노드는 클래스 ng-scope를 받기 때문에 다음과 같은 작업을 수행할 수 있습니다.

function getScope(id) {
var elem;
$('.ng-scope').each(function(){
    var s = angular.element(this).scope(),
        sid = s.$id;

    if(sid == id) {
        elem = this;
        return false; // stop looking at the rest
    }
});
return elem;
}

을 시험해보니 디렉티브는 수업이 없는 것 같다.ng-scope여기 모든 것을 폴백할 수 있는 수정된 버전이 있습니다.

var getByScopeId = function(id) { 
    var filterfn = function(i,el) {
        var sc = angular.element(el).scope();

        return sc && sc.$id == id;
    };
    // low hanging fruit -- actual scope containers
    var result = $('.ng-scope').filter(filterfn);
    if(result && result.length) return result;

    // try again on everything...ugh
    return $(':not(.ng-scope)').filter(filterfn);
}

사용방법:

var results = getByScopeId('003')

JQuery 종속성 없이 es2015년에 작성된 동일한 솔루션:

getElementFromScopeId = (id) => [].slice.call(document.querySelectorAll('.ng-scope')).map((x) => angular.element(x)).filter(x => x.scope().$id == id).pop();

격리된 스코프를 올바르게 검출해 처리해, 요소를 발견하면 곧바로 정지하는 버전입니다.각도.scope()그리고..isolateScope()함수는 jquery를 사용합니다..data()오브젝트 및 스코프를 찾을 수 없는 경우 요소의 부모 노드를 검색합니다.이미 모든 노드를 검색하고 있기 때문에 상위 검색을 건너뛰고 검사하는 것이 훨씬 효율적입니다..data()직접적으로.

const findScopeElement = $scope => {
    const {$id, $root} = $scope;
    let result;
    const isolate = $scope !== $root &&
        Object.getPrototypeOf($scope) === Object.getPrototypeOf($root);
    const cls = isolate ? '.ng-isolate-scope' : '.ng-scope';
    const search = (i, e) => {
        const data = $(e).data();
        const scope = isolate ? data.$isolateScope : data.$scope;
        if(scope && scope.$id === $id) {
            result = e;
            return false;
        }
    };
    $(cls).each(search);
    if(!result) {
        // could be an attribute directive
        $(`:not(${cls})`).each(search);
    }
    return result;
}

항상 요소의 ID를 사용하여 스코프를 가져올 수 있습니다.

예:

html:

<div id="myId"></div>

js:

  var myEl = angular.element(document.querySelector('#myId'));
  var myScope = angular.element(myEl).scope(); 

라이브 예:http://jsfiddle.net/choroshin/7XQA7/2/

또한 David Chase가 제안한 대로 언제든지 batarang - Extends Chrome Developer Tools를 사용할 수 있으며 Angular 디버깅 및 프로파일링을 위한 도구를 추가할 수 있습니다.JS 어플리케이션

언급URL : https://stackoverflow.com/questions/23253506/get-dom-element-by-scope-id

반응형