Reputation: 13636
I am creating a directive that will generate the HTML elements automatically according to data that received from the server.
Here is angularjs code:
(function () {
"use strict";
angular.module("workPlan").directive("myGenericFilter", ["$compile", "$http", "config", myGenericFilterData]);
function myGenericFilterData($compile, $http, config) {
var directive = {
restrict: "E",
scope: {
filterParams: "=filterparameters",
},
//templateUrl: config.baseUrl + "app/workPlan/templates/workPlanList.tmpl.html",
template: '<div></div>',
controller: "genericFilterDataController",
controllerAs: "filter",
link: function (scope, element) {
var parameters;
var el = angular.element('<span/>');
$http.post(config.baseUrl + "api/FilterConfigurations/", scope.filterParams).then(function (result) {
parameters = result.data;
angular.forEach(parameters, function (parameter, key) {
switch (parameter.ValueType) {
case 'Int32':
el.append('<div class="form-group">' +
'<div class="">' +
'<span class="view"></span>' +
'<input type="text"' + 'id =' + parameter.ObjectName + ' class="form-control">' +
'</div>' +
'</div>');
break;
case 'DateTime':
el.append('<div class="form-group">' +
'<span class="view"></span>' +
'<my-datepicker placeholder="dd/mm/yyyy" class=""></my-datepicker>' +
'</div>');
break;
}
});
});
$compile(el)(scope);
element.append(el);
}
}
return directive;
}
})();
As you can see I get data from server and according to parameter.ValueType
appropriate case selected in the switch.
After the angular.forEach
operator iterated on all items in the parameters
variable and all DOM elements is loaded, all input HTML elements displayed except my-datepicker
custom directive.
When I use F12 to Inspect Element I see the HTML code of all the elements(include my-datepicker
).
Here how it's looks:
But in the view my-datepicker
not displayed, here how it looks in view:
my-datepicker
is custom directive that defined in common module that injected in all moduls in my project.
Any idea why my-datepicker
not displayed in the view?
Upvotes: 0
Views: 42
Reputation: 2062
You compile el
before the content of el
is setted.
Remember that $http request is async then put
$compile(el)(scope);
element.append(el);
Into the callback
link: function (scope, element) {
var parameters;
var el = angular.element('<span/>');
$http.post(config.baseUrl + "api/FilterConfigurations/", scope.filterParams).then(function (result) {
parameters = result.data;
angular.forEach(parameters, function (parameter, key) {
switch (parameter.ValueType) {
case 'Int32':
el.append('<div class="form-group">' +
'<div class="">' +
'<span class="view"></span>' +
'<input type="text"' + 'id =' + parameter.ObjectName + ' class="form-control">' +
'</div>' +
'</div>');
break;
case 'DateTime':
el.append('<div class="form-group">' +
'<span class="view"></span>' +
'<my-datepicker placeholder="dd/mm/yyyy" class=""></my-datepicker>' +
'</div>');
break;
}
});
$compile(el)(scope);
element.append(el);
});
}
Upvotes: 1