What I am doing: I am creating two attribute directives: One moves an element to the left, and another centers an element on the page. See code below. Notice that I'm manipulating ng-style
to set those css properties (moving the element to the left, and centering on the page).
The Problem:
When I use both directives on an element, the second directive's scope.style={}
obviously overwrites the first one.
This means that I'm not able to apply both ng-style
/attributes at the same time.
My question:
What is an easy way to instantiate the scope.style
object so that I can use it in both directives without recreating the object?
I'm trying to find a simple solution that can be scaled easily for multiple element directives without writing tons of messy code. (I don't want to create a special controller inside every directive to accommodate sharing the scope.style object).
Please advise. Thanks a lot!
Here is the html:
The data is from a json file, but that's not important here.
<!-- The Element: -->
<started-box center-page keepleft screen="screen[3]"></started-box>
<!-- The Template: -->
<div id="{{screen.id}}" ng-style="$parent.style">
Some content goes here.
</div>
Here are the AngularJS code snippets:
// 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'
};
}]);