[angularjs] AngularJS에서 지시문을 동적으로 추가하려면 어떻게해야합니까?

나는 내가하고있는 일의 매우 삶은 버전을 가지고있어 문제가 발생합니다.

나는 간단하다 directive. 요소를 클릭 할 때마다 다른 요소가 추가됩니다. 그러나 올바르게 렌더링하려면 먼저 컴파일해야합니다.

나의 연구는 나를 이끌었다 $compile. 그러나 모든 예제는 여기에 적용하는 방법을 모르는 복잡한 구조를 사용합니다.

바이올린은 여기에 있습니다 : http://jsfiddle.net/paulocoelho/fBjbP/1/

그리고 JS는 여기 있습니다 :

var module = angular.module('testApp', [])
    .directive('test', function () {
    return {
        restrict: 'E',
        template: '<p>{{text}}</p>',
        scope: {
            text: '@text'
        },
        link:function(scope,element){
            $( element ).click(function(){
                // TODO: This does not do what it's supposed to :(
                $(this).parent().append("<test text='n'></test>");
            });
        }
    };
});

Josh David Miller의 솔루션 :
http://jsfiddle.net/paulocoelho/fBjbP/2/



답변

거기에 무의미한 jQuery가 많이 있지만 $ compile 서비스는 실제로이 경우 매우 간단합니다 .

.directive( 'test', function ( $compile ) {
  return {
    restrict: 'E',
    scope: { text: '@' },
    template: '<p ng-click="add()">{{text}}</p>',
    controller: function ( $scope, $element ) {
      $scope.add = function () {
        var el = $compile( "<test text='n'></test>" )( $scope );
        $element.parent().append( el );
      };
    }
  };
});

모범 사례를 따르기 위해 지시문을 리팩터링 한 것을 알 수 있습니다. 궁금한 점이 있으면 알려주세요.


답변

새로운 요소 지시문 을 추가하는 완벽한 Riceball LEE의 예 외에도

newElement = $compile("<div my-directive='n'></div>")($scope)
$element.parent().append(newElement)

기존 요소에 새 속성 지시문 을 추가하는 방법은 다음과 같습니다.

요소에 즉석 my-directive에서 추가하고 싶다고 가정 해 봅시다 span.

template: '<div>Hello <span>World</span></div>'

link: ($scope, $element, $attrs) ->

  span = $element.find('span').clone()
  span.attr('my-directive', 'my-directive')
  span = $compile(span)($scope)
  $element.find('span').replaceWith span

희망이 도움이됩니다.


답변

angularjs에 지시문을 동적으로 추가하는 데는 두 가지 스타일이 있습니다.

다른 지시문에 angularjs 지시문 추가

  • 새로운 요소 삽입 (지시문)
  • 요소에 새로운 속성 (directive) 삽입

새로운 요소 삽입 (지시문)

간단 해. 그리고 “link”또는 “compile”에서 사용할 수 있습니다.

var newElement = $compile( "<div my-diretive='n'></div>" )( $scope );
$element.parent().append( newElement );

요소에 새로운 속성 삽입

힘들고 이틀 안에 두통이납니다.

“$ compile”을 사용하면 심각한 재귀 오류가 발생합니다 !! 요소를 다시 컴파일 할 때 현재 지시문을 무시해야 할 수도 있습니다.

$element.$set("myDirective", "expression");
var newElement = $compile( $element )( $scope ); // critical recursive error.
var newElement = angular.copy(element);          // the same error too.
$element.replaceWith( newElement );

따라서 지시문 “link”함수를 호출하는 방법을 찾아야합니다. 클로저 안에 깊이 숨겨져있는 유용한 메소드를 얻는 것은 매우 어렵습니다.

compile: (tElement, tAttrs, transclude) ->
   links = []
   myDirectiveLink = $injector.get('myDirective'+'Directive')[0] #this is the way
   links.push myDirectiveLink
   myAnotherDirectiveLink = ($scope, $element, attrs) ->
       #....
   links.push myAnotherDirectiveLink
   return (scope, elm, attrs, ctrl) ->
       for link in links
           link(scope, elm, attrs, ctrl)       

이제 잘 작동합니다.


답변

function addAttr(scope, el, attrName, attrValue) {
  el.replaceWith($compile(el.clone().attr(attrName, attrValue))(scope));
}


답변

Josh David Miller의 답변은 인라인을 사용하는 지시문을 동적으로 추가하려는 경우 효과적 template입니다. 그러나 귀하의 지시가 templateUrl그의 답변을 활용 하면 작동하지 않습니다. 다음은 나를 위해 일한 것입니다.

.directive('helperModal', [, "$compile", "$timeout", function ($compile, $timeout) {
    return {
        restrict: 'E',
        replace: true,
        scope: {},
        templateUrl: "app/views/modal.html",
        link: function (scope, element, attrs) {
            scope.modalTitle = attrs.modaltitle;
            scope.modalContentDirective = attrs.modalcontentdirective;
        },
        controller: function ($scope, $element, $attrs) {
            if ($attrs.modalcontentdirective != undefined && $attrs.modalcontentdirective != '') {
                var el = $compile($attrs.modalcontentdirective)($scope);
                $timeout(function () {
                    $scope.$digest();
                    $element.find('.modal-body').append(el);
                }, 0);
            }
        }
    }
}]);


답변

조쉬 데이비드 밀러가 맞습니다.

PCoelho, 궁금한 점이 있으시면 $compile 배후에서 이 지시문에서 HTML 출력이 생성되는지 아래를 살펴보십시오.

$compile서비스 "< test text='n' >< / test >"는 지시문 ( “test”를 요소로 포함)을 포함하는 HTML ( ) 조각을 컴파일하고 함수를 생성합니다. 그런 다음이 함수를 범위와 함께 실행하여 “지시문의 HTML 출력”을 얻을 수 있습니다.

var compileFunction = $compile("< test text='n' > < / test >");
var HtmlOutputFromDirective = compileFunction($scope);

전체 코드 샘플에 대한 자세한 내용은 다음을 참조 하십시오.
http://www.learn-angularjs-apps-projects.com/AngularJs/dynamically-add-directives-in-angularjs


답변

이전의 많은 답변에서 영감을 얻어 다른 지시어로 대체 할 다음 “stroman”지시문을 작성했습니다.

app.directive('stroman', function($compile) {
  return {
    link: function(scope, el, attrName) {
      var newElem = angular.element('<div></div>');
      // Copying all of the attributes
      for (let prop in attrName.$attr) {
        newElem.attr(prop, attrName[prop]);
      }
      el.replaceWith($compile(newElem)(scope)); // Replacing
    }
  };
});

중요 사항 : 에 사용할 지시문을 등록하십시오 restrict: 'C'. 이처럼 :

app.directive('my-directive', function() {
  return {
    restrict: 'C',
    template: 'Hi there',
  };
});

다음과 같이 사용할 수 있습니다 :

<stroman class="my-directive other-class" randomProperty="8"></stroman>

이것을 얻으려면 :

<div class="my-directive other-class" randomProperty="8">Hi there</div>

Protip. 클래스를 기반으로 한 지시문을 사용하지 않으려면 원하는 것으로 변경할 수 있습니다 '<div></div>'. 예를 들어, 대신 원하는 지시문의 이름을 포함하는 고정 된 속성이 있습니다 class.