I have a question regarding form validation. It is not working for me in the following scenario:
I have a global form, inside the form dynamic fields are rendered using a directive. That directive based on the type of my field appends a recently compiled directive to the doom.
here is the directive:
app.directive('render', function($compile){
return {
scope: {model: '='},
restrict: 'A',
replace: true,
template:
'<div class="product-option-selector">'+
'</div>',
link: function(scope, element){
var directive = null;
switch(scope.model.type){
case 'number':
directive =
'<div data-item-number data-model="model"></div>';
break;
case 'text':
var directive =
'<div data-item data-model="model"></div>';
break;
case 'radio':
var directive =
'<div fg-product-option-selector-radio option="option" item="item" index="index"></div>';
break;
}
if(!directive) return;
directive = '<div>'+directive+'</div>';
$(element).append($compile(directive)(scope));
}
}
});
app.directive('item', function(){
return {
scope: {model: '='},
restrict: 'A',
replace: true,
template:
'<ng-form name="innerForm">'+
'{{model.name}}'+
'<input type="text" name="innerVal" ng-model="model.value" required></input>'+
'</ng-form>'
}
});
app.directive('itemNumber', function(){
return {
scope: {model: '='},
restrict: 'A',
replace: true,
template:
'<ng-form name="innerForm">'+
'{{model.name}}'+
'<input type="number" name="innerVal" ng-model="model.value" required></input>'+
'</ng-form>'
}
});
I have a button in the form that must be disabled when the form is invalid. The problem is that the button is never disabled.
the html code:
<div ng-controller="basicController">
<form name="form">
<div ng-repeat="f in fields">
<div data-render data-model="f"></div>
</div>
<button ng-disabled="form.$invalid">submit</button>
</form>
</div>
my jsFindle link: http://jsfiddle.net/8rz6U/1/
This is a simplification of my problem in the app. the fields directives are more complex, but the code is here.
Thank you,
I found solution for this issue, in this Q & A: AngularJS: Error: No controller: form. The trick is:
Here is the changed code snippet:
directive = '<div>'+directive+'</div>';
// Do Not compile the element NOT beeing part of the DOM
//$(element).append($compile(directive)(scope));
// Firstly include in the DOM, then compile
var result = $(directive).appendTo(element);
$compile(result)(scope);
Here is working jsfiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With