实例化一个对象,使其可以与多个指令共享



我正在做的事情:我创建两个属性指令:一个将元素向左移动,另一个将一个元素居中放置在页面上。请参阅下面的代码。请注意,我正在操作ng-style来设置那些css属性(将元素向左移动,并以页面为中心)。

问题:
当我在一个元素上同时使用两个指令时,第二个指令的scope.style={}显然会覆盖第一个指令
这意味着我不能同时应用两个ng-style/属性。

我的问题:
实例化scope.style对象的简单方法是什么,这样我就可以在两个指令中都使用它,而无需重新创建对象?

我正试图找到一个简单的解决方案,它可以很容易地扩展多元素指令,而不需要编写大量混乱的代码。(我不想在每个指令中创建一个特殊的控制器来容纳共享scope.style对象)。

请告知。非常感谢!


这是html:
数据来自json文件,但这在这里并不重要

<!-- 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>

以下是AngularJS代码片段:

// 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'
    };
}]);

创建一个样式服务并将其注入两个指令中。服务非常适合在指令/控制器之间共享状态。

最新更新