I am working on developing a directive that will allow me to create temporary variables within the scope of an HTML tag. This directive will only apply within the specific tag I am rendering. Here is an example use case:
<div class="input-group" ng-local="opened = false" ng-blur="opened = false;">
<input type="text" class="form-control" uib-datepicker-popup="longDate" ng-model="start" is-open="opened" ng-focus="opened = true;" />
<span class="input-group-btn">
<button type="button" ng-click="opened = true;" class="fa fa-calendar" ></button>
</span>
</div>
In this scenario, the ng-local directive creates a variable called opened
and initializes it with a value of false
. The content inside the directive is a transcluded template. The benefit of this approach is that multiple datepickers on a page can all share the same variable opened
, eliminating the need for separate variables in the scope or controller just for temporary use within a div. However, I want this directive to be versatile enough to handle different use cases without creating multiple variations.
While my initial implementation was successful, I encountered a problem where the parent scope variable start
was not being accessed correctly by the datepicker component. Since I am not very experienced with the $transclude functionality, I am seeking guidance from someone who can help me troubleshoot this issue. Below is the current version of the directive I have implemented:
(function () {
angular.module('myApp').directive('ngLocal', [function () {
return {
restrict: 'A',
transclude: 'element',
replace: false,
scope: {
ngLocal: '@'
},
link: function ngLocalLink(directiveScope, element, attrs, ctrl, $transclude) {
$transclude(directiveScope, function ngLocalTransclude(clone, scope) {
element.empty();
element.replaceWith(clone);
scope.$eval(directiveScope.ngLocal);
});
}
};
}]);
})();
Any insights or suggestions would be greatly appreciated!
EDIT
For reference, here's a plunkr link: