0
我在做什么:我正在创建两个属性指令:一个将元素移动到左侧,另一个移动元素在页面上居中。见下面的代码。请注意,我操纵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'
};
}]);
我添加了以下服务。问题是使用任何一个属性指令在所有元素之间共享相同样式的对象。这意味着如果一个元素只使用其中一个属性指令,它仍然适用于它。我如何隔离这个以每个元素重新创建一次样式对象?非常感谢您的回答。 app.factory(“style”,function(){ return { style:{} } }); – dragonfire