Background
I am building a custom form building directive. Yes, I am aware that there are many out there already, thanks.
Using ngModel
from within my directive, I loop through a JSON array of control objects for my form:
$scope.myForm.controls = [{label: "foo", controlType: "input"}, {label: "bar", controlType: "checkbox"}];
From there, the plan is to $compile
in individual directives for each form control.
Here is the primary directive (working fine):
app.directive('myDynamicForm', ['$compile', function ($compile) {
return {
restrict: 'E', // supports using directive as element only
scope: {
ngModel: "="
},
replace: true,
link: function (scope, element, attrs) {
angular.forEach(scope.ngModel, function (model) {
var el = "";
switch (model.controlType.toLowerCase()) {
case "input":
el = "<my-input ng-model='model'></my-input>";
break;
default:
break;
}
$compile(el)(scope);
element.append(el);
});
}
};
}])
Here is the usage:
<my-dynamic-form ng-model="myForm.controls"></my-dynamic-form>
Again, this part works fine.
Problem
As I create those new directive-based elements, I need to pass to them--as their ng-model--the specific object being iterated over in the forEach
loop of the prime directive.
So, here is an example control directive:
directive('myInput', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: {
ngModel: "="
},
replace: true,
templateUrl: "/templates/input.html",
link: function (scope, element) {
var obj = scope.ngModel; //<==SHOULD BE SAME AS "model" IN THE FORM BUILDING DIRECTIVE!!
}
};
}])
Usage:
<myInput ng-model="[model from parent form building directive]"></myInput>
Right now, if I set the ng-model of the child directive to <my-input ng-model='ngModel'></my-input>
, I get the same collection that the parent directive is iterating.
If I set it to "model" <my-input ng-model='model'></my-input>
I get undefined
as the value of the child directive.
Any help is appreciated.