Saturday, 15 March 2014

javascript - Dynamic templates rendered using directive scope variables -



javascript - Dynamic templates rendered using directive scope variables -

trying find way render forms different controls based on type variable specified in json document. form going generated user input, don't know question types need render. define types are, can come in order user.

{ "name": "getting know you.", "id": "870tvcee8irpldhi14fszw==", "controls": [ { "type": "text", "label": "first name", "id": "vf4z8ycslpjgsf9fdw5tpa==", "color": "ffffff", "required": "true", "validaion": "false", "validationregex": "", "errortext": "" }, { "type": "picklist", "label": "last name", "id": "vf4z8ycslpjgsf9fdw5tpa==", "color": "#cccccc", "required": "true", "validaion": "false", "validationregex": "", "errortext": "", "picklistvals": ["1","3","5"] } ] }

the directive needs read command type, pass directive figure out template render.

<div ng-repeat="control in section.controls"> <input-parser ele="{{control}}"></input-parser> </div> app.directive('inputparser', function() { function gettemplate (control) { var template = ''; switch(control.type) { case 'text': template = '<form style="color:' + control.color + '">template2</form>'; break; case 'picklist': template = '<form style="color:' + control.color + '">template2</form>'; break; } homecoming template; } homecoming { restrict: "e", scope: { control: '@' }, template: function() { homecoming gettemplate(control)); } }

two questions:

can access scope variables in template attribute of directive loaded dynamically ? can seem hard code them because bindings not set before directive if parsed.

is way render dynamic templates need need access info passed directive. should access root scope , forget scope variables?

if input-parser directive renders form , nil else how consider using ng-include instead, , place templates partial.

demo

<ng-include ng-repeat="control in section.controls" src="control.type + '.html'"></ng-include>

but if input-parser directive have sort of behavior want share across templates, can utilize ng-include above template instead.

javascript

.directive('inputparser', function() { homecoming { restrict: 'e', scope: { control: '=' }, template: '<ng-include src="\'form\' + control.type + \'.html\'"></ng-include>' // controller: function() {}, // attach controller behaviour // link: function() {} // attach element behaviour }; });

html

<input-parser ng-repeat="control in section.controls" control="control"></input-parser>

javascript angularjs angularjs-directive

No comments:

Post a Comment