Changing direction in Angular
I am trying to change sp-right class to sp-left programticlyly in angular:
Html
<span class="sp-right">
<label>
Number:
</label>
</span>
Directive
app.directive("buttonThatTrigger", function () {
return {
restrict: 'C',//target all elements with class button-that-trigger
link: function (scope, element, attrs) {
element.click(function(){
$('.sp-right, .sp-left').toggleClass("sp-right sp-left");
});
}
};
});
It works great, but when I click on the link (ui-router) and come back, it changes to the original!
Any idea?
+1
user3856699
source
to share
2 answers
I don't know what your requirements are, but is there a reason why you are not using ngClass?
<div ng-class='whatClassIsIt(position)' ng-click='position = !position'>
Then you do
$scope.position = true;
// true=sp-right, false=sp-left
$scope.whatClassIsIt(pos){
return pos? "sp-right" : "sp-left";
};
0
source to share
You have to remember the state (in your case the direction) either in the controller that is in a level (like in the body) that will not be replaced by ui-router or (IMO preferable) you remember the state in the service ( .service|.factory|.value
).
Example:
app.value('layoutState', {
direction: 'right'
});
And when you have the state in a safe place, you can change your implementation in a more "boxy" way:
<span class="{{layoutState.direction === 'right' ? 'sp-right' : 'sp-left'}}">
<label>
Number:
</label>
</span>
Your directive:
app.directive("buttonThatTrigger", ['layoutState', function (layoutState) {
return {
restrict: 'C',//target all elements with class button-that-trigger
link: function (scope, element, attrs) {
scope.layoutState = layoutState;
element.click(function(){
layoutState.direction = layoutState.direction === 'right' ?
'left' : 'right';
});
}
};
}]);
0
source to share