【问题标题】:Instantiate an object so it can be shared with multiple directives实例化一个对象,以便它可以与多个指令共享
【发布时间】:2016-03-07 00:53:23
【问题描述】:

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

问题:
当我在一个元素上使用 both 指令时,第二个指令的 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 代码 sn-ps:

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

【问题讨论】:

    标签: javascript css angularjs angularjs-scope ng-style


    【解决方案1】:

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

    【讨论】:

    • 我添加了以下服务。问题是使用任一属性指令在所有元素之间共享相同的样式对象。这意味着,如果一个元素仅使用其中一个属性指令,那么它仍然同时应用了这两个属性指令。如何隔离它以每个元素重新创建一次样式对象?非常感谢您的回答。 app.factory("style", function(){ return{ style: {} } });
    猜你喜欢
    • 2011-07-09
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多