Reputation: 536
I am working on a angular js project. Right now the controls are static. But client wants to create the html controls based on database.
I have a table with controls specification
For eg:
type : text/dropdown/radio/checkbox
events : onchange/onblur/onfocus
attributes:"color:red"
How can I generate the dynamic model which can parse database value to html controls?
Any help would be really appreciated...
Upvotes: 1
Views: 3985
Reputation: 439
This is pretty easy using the ng-repeat directive. Note how I assign the value of the model back to the scope variable in the ng-repeat. This allows me to retrieve it later.
angular.module('formModule', []).
controller('DynamicFormController', ['$scope',
function($scope) {
//Set equal to json from database
$scope.formControls = [{
name: "Name",
type: "text"
}, {
name: "Age",
type: "number",
color: "red"
},
{
name: "UseNestedControls",
type: "checkbox",
nestCondition: true,
nestedControls: [{
name: "NestedText",
type: "text"
}]
}
];
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="formModule">
<div ng-controller="DynamicFormController">
<form>
<div ng-repeat="input in formControls">
<label>{{input.name}}</label>
<input type="{{input.type}}" ng-model="input.value" ng-style="{'color':input.color}" />
<div ng-repeat="nestedInput in input.nestedControls" style="margin-left:20px" ng-show="input.value == input.nestCondition">
<label>{{nestedInput.name}}</label>
<input type="{{nestedInput.type}}" ng-model="nestedInput.value" ng-style="{'color':nestedInput.color}"/>
</div>
</div>
</form>
<div ng-repeat="input in formControls">
<span>{{input.name}} = {{input.value}}</span>
<div ng-repeat="nestedInput in input.nestedControls" style="margin-left:20px">
<span>{{nestedInput.name}} = {{nestedInput.value}}</span>
</div>
</div>
</div>
</body>
Upvotes: 3