2015-12-02 54 views
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' 
    }; 
}]); 

回答

1

創建一個風格服務,並將它注入到這兩個指令。服務非常適合在指令/控制器之間共享狀態。

+0

我添加了以下服務。問題是使用任何一個屬性指令在所有元素之間共享相同樣式的對象。這意味着如果一個元素只使用其中一個屬性指令,它仍然適用於它。我如何隔離這個以每個元素重新創建一次樣式對象?非常感謝您的回答。 app.factory(「style」,function(){ return { style:{} } }); – dragonfire

相關問題