Currently, I am exploring the capabilities of angularjs and aiming to dynamically load directives only when they are required instead of loading all of them initially on the page. My focus is on creating custom directives for the plugins that I use frequently.
To achieve this, I plan to utilize yepnope
to load the necessary directives before compiling the html.
When a directive is loaded along with others at the start of the page, everything functions as expected. However, if a 'child' directive is loaded later within the 'parent' directive, it does not seem to have any impact. The code snippet below demonstrates how the pre field works within the compile field of the 'parent' directive.
...
var pre = function (scope, element, attrs) {
element.html('Please wait. Loading...');
ang.loadDirectives('caiDatePicker', function () {
console.log('loaded');
scope.data.raw = scope.rawData;
var html = createObjUi(scope, scope.data, scope.defn);
element.html(html); //data
$compile(element.contents())(scope.$new());
scope.$apply();
});
};
return { restrict:'A', compile: {pre:pre,post:function(){...}};
ang.loadDirectives
is responsible for loading the directive using yepnope. Here is a portion of the code related to the implementation of the 'child' directive:
angular.module('mycomponents') //PS: I'm assuming this will fetch the already created module in the 'parent' directive
.directive('caiDatePicker', function ($parse) {
return {
scope: {},
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch('this.$parent.editing', function (v) {
scope.editing = v;
});
yepnope({
test: $().datePicker,
nope: [
'/content/plugins/datepicker/datepicker.js', //todo: use the loader
'/content/plugins/datepicker/datepicker.css'
],
complete: function () {
if (scope.model && scope.model.value) {
var date = scope.model.value;
element.val(date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear());
}
element.datepicker({ weekStart: 1, format: 'dd/mm/yyyy' })
.on('changeDate', function (ev) {
scope.model.value = ev.date;
scope.$apply();
});
}
});
attrs.$observe('path', function (v) {
var fn = $parse(v);
var model = fn(scope.$parent);
scope.model = model;
});
}
}
});
Is it feasible for me to accomplish what I intend to do?
If so, can you point out where I might be going wrong?