【发布时间】: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