I'm encountering a significant issue with dynamic directives in angularjs.
My goal is to include new directives to a directive while defining it through an object:
compile: function () {
return {
pre: function (scope, iElement, iAttrs) {
// In this scenario, cbAttrs is an object {cbSuggest: true, cbDatepicker: true}, as an example
scope.objects = JSON.parse(iAttrs.cbAttrs);
if (!iAttrs.compiled) {
angular.forEach(scope.objects, function(props) {
for (var prop in props) {
iAttrs.$set(prop, (typeof props[prop] === 'object' ? JSON.stringify(props[prop]) : props[prop]));
}
});
iAttrs.$set('dataCompiled', true);
$compile(iElement)(scope);
}
}
};
}
I have managed to get it working this way. However, I am unsure if this is the correct approach and I cannot grasp why I need to compile the element during the PRE compiling stage of the directive.
Moreover, when added this way, the input behaves strangely. For instance, attempting to move left inside the input and then deleting a letter will cause the cursor to jump to the end of the input.
I also tried within the link function, which resulted in the same odd behavior for the input:
link: function(scope, elem, attrs) {
scope.objects = JSON.parse(attrs.cbAttrs);
if (!attrs.compiled) {
angular.forEach(scope.objects, function(props) {
for (var prop in props) {
attrs.$set(prop, (typeof props[prop] === 'object' ? JSON.stringify(props[prop]) : props[prop]));
}
});
attrs.$set('dataCompiled', true);
$compile(elem)(scope);
}
}
To be honest, I am running out of ideas. I did see the comment with the template example, but I prefer not to set the return element hardcoded.
Check out the Plunker showcasing both issues: http://plnkr.co/edit/tbQubTMarjxB8ogzhtey?p=preview And the jsFiddle link: http://jsfiddle.net/plantface/Lwktcyu7/