angularjs - How do I store angular directive in a scope variable? -
i implementing form builder in angularjs , need insert , reorder directives @ runtime. don't know start looking - examples seem demonstrate static tree of directives. 2 options achieve dynamic behaviour are: a) compiling , inserting templates on fly , b) using huge ng-switch of possible directives. both ways ugly.
can suggest better implementation?
below js , html code how think formbuilder should in ideal world, please me fill in 3 instances of todo.
jsfiddle javascript:
angular.module('components', []) .directive('checkbox', function() { return { restrict: 'e', template: '<div class=f><input type=checkbox>{{name}}</input></div>' }; }) .directive('textfield', function() { return { restrict: 'e', template: '<div class=f><input type=text placeholder="{{name}}"></input></div>' }; }) function formbuilder($scope, $locale) { $scope.title = 'test form'; $scope.fields = []; $scope.add_checkbox = function() { console.log('adding checkbox'); var field = null; // todo: how instantiate directive? $scope.fields.push(field); }; $scope.add_textfield = function() { console.log('adding textfield'); var field = null; // todo: how instantiate directive? $scope.fields.push(field); }; }
html:
<div ng-app=components ng-controller=formbuilder> <button ng:click="add_checkbox()">new checbox</button> <button ng:click="add_textfield()">new text field</button> <h3>{{ title }}</h3> <checkbox></checkbox> <textfield></textfield> <div ng:repeat="field in fields"> <!-- todo field.get_html() - how? --> </div> </div>
i think have couple ways mentioned , since don't want switch can create template file each directive. ie checkbox.html, textfield.html , put directive in each one. populate fields array ['checkbox.html', 'textarea.html']
when add in loop <div ng-include='field'></div>
here demo: http://plnkr.co/edit/w6n6xpng6rp5wjhdlj3y?p=preview
you create directive pass in input type , have inject template. here demo of allows avoid having declare templates , letting directive create them based on field type:
http://plnkr.co/jhwgumxztuspz8otsvry
<div ng:repeat="field in fields"> <master-field type='field'></master-field> </div>
this master-field directive compiles template based on value of field.
.directive('masterfield', function($compile) { return { restrict: 'e', replace:true, transclude: true, scope:{ type:'=' }, template: '<div></div>', controller: function ( $scope, $element, $attrs ) {}, link: function(scope, element, attrs) { element.append( $compile('<' + scope.type+ '/></' +scope.type + '>')(scope) ); } }; })
Comments
Post a Comment