2014-12-11 2 views
0

이 실행 가능한 예제를 고려() .children로 변환 :AngularJS와 지침 jqLite는 .contents()가

var app=angular.module('myapp', []) 
 
.directive('mydct', function() { 
 
    return { 
 
    restrict:'EA', 
 
    transclude:true, 
 
    template:"<div>Template</div>", 
 
    replace:true, 
 
    scope:true, 
 
    link: function (scope, elm, attrs,ctrl,transcludeFn) { 
 
     transcludeFn(function(clone, scope) { 
 
     console.log(clone[0]); 
 
     console.log(clone[1]); 
 
     console.log(clone[2]); 
 
     console.log(clone[3]); 
 
     //clone[3].attr('id'); 
 
     }); 
 
    } 
 
    }; 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<body ng-app='myapp'> 
 
    <mydct> 
 
    <div id='one'>This is one</div> 
 
    <span id='two'>This is two</span> 
 
    </mydct> 
 
</body>

당신이 transcludeFunction의 복제 매개 변수로 객체를 반환합니다 볼 수 있듯이. 내용(). 여기에는 텍스트 노드가 포함됩니다. 나는 두 가지 질문을 가지고있다.

  1. 이 내용 배열을 자식 배열로 변환하여 텍스트 노드를 생략하는 방법이 있습니까?
  2. 알다시피 배열의 요소에 액세스 할 때 텍스트 내용을 가져올 것입니다. 요소로 가져오고 특성을 가져올 수 있도록하려면 어떻게해야합니까?

답변

1
transcludeFn(function(clone, scope) { 
    var els, i; 

    // convert to a normal array 
    els = Array.prototype.slice.call(clone); 

    // exclude text nodes 
    els = els.filter(function (element) { 
     return element.nodeType !== Node.TEXT_NODE; 
    }); 

    // wrap each DOMElement in a jqLite object 
    for (i = 0; i < els.length; i++) { 
     els[i] = angular.element(els[i]); 
    } 

    for (i = 0; i < els.length; i++) { 
     // do what you like with each clone's attribute 
     console.log(els[i].attr('id')); 
    } 
}); 

이 통과하는 단계를 강조하지만 필요한 코드를 단순화하거나 단축 주시기 조금 장황 .

+0

오, 이런,이게 복잡한가요? 특히 목록에서 요소를 선택할 때마다 angular.element를 호출해야합니까? – user1506145

+1

'clone' 배열에 포함 된 요소는 기본적으로 jqLite/jQuery로 래핑되지 않으므로 jqLite 메소드를 사용하려면 예를 들어 래핑해야합니다. 또는 네이티브 DOM API 만 사용할 수도 있습니다. id 속성의 값을 얻으려면, 예를 들어'element.getAttribute ('id')'를 사용하십시오. – user2943490