My Current Project: I am currently working on developing two attribute directives. One directive is designed to move an element to the left, while the other centers an element on the page. Below is a snippet of the code showcasing how I am using ng-style
to manipulate CSS properties for moving the element left and centering it on the page.
The Issue at Hand:
The problem arises when both directives are applied to the same element. In this scenario, the second directive's scope.style={}
will overwrite the settings from the first one. Consequently, it becomes impossible to simultaneously apply both ng-style
attributes.
My Query:
I am seeking advice on a simple way to initialize the scope.style
object so that it can be shared across both directives without needing to recreate the object repeatedly. My goal is to find a straightforward solution that can easily scale for multiple element directives without resorting to writing convoluted code or creating separate controllers within each directive.
Your input and suggestions would be greatly appreciated. Thank you!
Sample HTML Code:
The data source is a JSON file, but it's not vital for this discussion.
<!-- Element in Use: -->
<started-box center-page keepleft screen="screen[3]"></started-box>
<!-- Corresponding Template: -->
<div id="{{screen.id}}" ng-style="$parent.style">
Content goes here.
</div>
AngularJS Snippets:
// Definition of Two Attribute Directives:
app.directive("centerPage", function () {
return function (scope, element, attrs) {
var winW = window.innerWidth;
var winH = window.innerHeight;
var boxW = 370;
var boxH = 385;
scope.style = {};
scope.style.left = (winW / 2) - (boxW / 2);
scope.style.top = (winH / 2) - (boxH / 2);
}
});
app.directive("keepleft", function () {
return function (scope, element, attrs) {
scope.style = {};
scope.style.cursor = 'default';
scope.style.transform = 'translateX(-60%)';
}
});
// Directive for the Template:
app.directive("startedBox", [function () {
return {
restrict: "E",
replace: true,
scope: {
screen: '='
},
templateUrl: dir + 'templates/directives/started-box.html'
};
}]);