2013-08-31 2 views
4

지시어 이름의 구성 배열을 기반으로 지시문을 동적으로 렌더링하려합니다. 이것은 각도로 가능합니까? 나는 또한 (당신이 NG 반복와 마찬가지로)이 렌더링 된 지침이부모 지시어 또는 컨트롤러에서 지시어 이름 배열에서 AngularJS 지시문을 렌더링

http://jsfiddle.net/7Waxv/

var myApp = angular.module('myApp', []); 

myApp.directive('one', function() { 
    return { 
     restrict: 'A', 
     template: '<div>Directive one</div>' 
    } 
}); 

myApp.directive('two', function() { 
    return { 
     restrict: 'A', 
     template: '<div>Directive two</div>' 
    } 
}); 

function MyCtrl($scope) { 
    $scope.directives = ['one', 'two']; 
} 

<div ng-controller="MyCtrl"> 
    <div ng-repeat="directive in directives"> 
     <div {{directive}}></div> 
    </div> 
</div> 

편집 한 부모 DOM 요소가 아닌 각지고 새로운 래퍼 내에서 살고 싶어이를 올리기 때문에 , I 시도해 보았습니다 :

.directive('parentDirective', function() { 
    return { 
    restrict: 'A', 
    replace: true, 
    link: function (scope, element) { 
     scope.directives = ['one', 'two']; 
     for (var i = 0; i < scope.directives.length; i++) { 
     element.prepend('<div ' + scope.directives[i] + '></div>') 
     } 
    } 
    }; 
}); 

<div parent-directive></div> 

이렇게하면 앞에 붙은 지시문의 템플릿이 렌더링되지 않습니다. 그래서 두 번째 시도 일 것이다

답변

5

를 ... 해결 방법은 매우 다양합니다 하지만 $scope.directives 배열을 마음대로 수정할 수 있으며 지시문이 동적으로 조작됩니다. 또한 현재 범위의 특정 속성을 가리켜 지시문 목록을 검색 할 수 있습니다.

Demo link

는 app.js

var myApp = angular.module('myApp', []); 

myApp.directive('one', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     template: '<div>Directive one</div>' 
    } 
}); 

myApp.directive('two', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     template: '<div>Directive two</div>' 
    } 
}); 

myApp.directive('dynamic', function ($compile, $parse) { 
    return { 
    restrict: 'A', 
    replace: true, 
    link: function (scope, element, attr) { 
     attr.$observe('dynamic', function(val) { 
     element.html(''); 
     var directives = $parse(val)(scope); 
     angular.forEach(directives, function(directive) { 
      element.append($compile(directive)(scope)); 
     }); 
     }); 
    } 
    }; 
}); 

function MyCtrl($scope) { 
    $scope.directives = ['<one/>', '<two/>']; 
    $scope.add = function(directive) { 
     $scope.directives.push(directive); 
    } 
} 

<div ng-controller="MyCtrl"> 
    <div dynamic="{{directives}}"></div> 
    <button ng-click="add('<one/>')">Add One</button> 
    <button ng-click="add('<two/>')">Add One</button> 
</div> 
+1

보다는 사용이'element.append', 당신은 제한 '설정에 대한 생각 했 index.html을' 요소에 대한 클래스를 업데이트하고 있습니까? 이 방법으로 지시문을 기존 DOM 요소에 추가하거나 새 DOM 요소를 만들 때 지시문을 추가 할 수 있습니다. – pedalpete

0

내가 그렇게처럼 앞에 추가 지침에 컴파일 $를 사용했다 : 나는 (오랜 시간이 걸렸) 해낸 다음

.directive('parentDirective', function($compile) 
    .... 
element.prepend($compile('<div ' + scope.directives[i] + '"></div>')(scope)); 
관련 문제