I am using Angularjs version 1.5 to validate the inputs in my form.
- ng-required is used to validate the all input required
However, its not working with a custom directive which renders a combo. The combo retrieves the items based on parameter passed to it named 'listId'. Then, it iterates on the 'lookupItems' using ng-repeat. I guess something is missing, like ngModel. Why and how to implement it?
The combo directive:
app.directive('combo', function($http) {
return {
restrict: 'AE',
template: '<div class="input-group"> <select ng-model="selectedItem">' +
'<option ng-repeat="option in lookupItems" value={{option.ListValueID}}>{{option.Translation.Value}}</option></select>' +
' {{selectedItem}} </div>',
replace: true,
scope: {
listId: '=',
defaultItem: '=',
selectedItem: '='
},
controller: function($scope) {
$http({
method: 'GET',
url: '/home/listvalues?listid=' + $scope.listId
}).then(function(response) {
$scope.lookupItems = response.data;
}, function(error) {
alert(error.data);
});
},
link: function(scope, element, attrs) {}
};
});
The html view: is iterating over attributes which contains the type of control to render, then its set ng-required to a boolean based on 'attribute.Required' which is true.
<form name="profileAttributesForm" ng-controller="metadataCtrl" class="my-form">
<div ng-repeat="a in attributes">
<div ng-if="a.DataType == 1">
<input type="text" name="attribute_{{$index}}" ng-model="a.Value" ng-required="a.Required" />
<span ng-show="profileAttributesForm['attribute_{{$index}}'].$invalid">Enter a Text</span> text : {{a.Value}}
</div>
<div ng-if="a.DataType == 4">
<div combo list-id="a.LookUpList" name="attribute_{{$index}}" selected-item="a.Value" ng-required="a.Required"></div>
<span ng-show="profileAttributesForm['attribute_{{$index}}'].$invalid">lookup Required</span> Value from lookup: {{a.Value}}
</div>
</div>
</form>
Sample of attributes ($scope.attributes) which is iterated over in the form, I am providing it just for illustration purposes:
[{
"AttributeID": 1,
"DataType": 4,
"NodeID": 0,
"Name": "Name",
"Description": null,
"LookUpList": 1,
"SortAscending": false,
"Required": true,
"DefaultValue": "1",
"Order": 1,
"Value": ""
}, {
"AttributeID": 3,
"DataType": 1,
"NodeID": 0,
"Name": "Job Title",
"Description": null,
"LookUpList": 0,
"SortAscending": false,
"Required": true,
"DefaultValue": null,
"Order": 2,
"Value": ""
}, {
"AttributeID": 4,
"DataType": 1,
"NodeID": 0,
"Name": "Email",
"Description": null,
"LookUpList": 0,
"SortAscending": false,
"Required": true,
"DefaultValue": null,
"Order": 3,
"Value": ""
}]