Reputation: 65
I've got a problem with angularjs and even after research I just couldn't find where I'm wrong.
I need to recalculate the css value "left" for an element. I'm using the 'ng-style' directive and a method that will return an object with the css value. Thats - afaik - what I have to do. But when I update the value, it wont update the style.
ng-bind usage:
<div ng-style="getCssShiftObject()">
method to create object
$scope.getCssShiftObject =function(){
return {'left':this.cssShift+'px'};
};
method to change the object
$scope.nextPosition = function(){
if((this.currentPosition+1) <= this.maxPosition){
this.currentPosition = this.currentPosition+1;
this.cssShift = (this.currentPosition*this.slideSize)*-1;
}
return this.currentPosition;
};
It will update at another place in the content when I use it like that:
{{getCssShiftObject()}}
I hope you can give mit a hit, thanks for your time!
Upvotes: 2
Views: 5004
Reputation: 13767
I had a similar problem with the style attribute. My binding was not working in some browsers, especially IE. I solved it by using ng-attr-style="{{yourBindingExpression}}".
Read more about ng-attr interpolation at https://docs.angularjs.org/guide/interpolation
Upvotes: 1
Reputation: 121
I came across a similar problem. I was trying to use ngStyle to load a background image, but if the variable in an expression is not immediately available (which might be the case if it's part of a resource promise), it won't work.
To address this, I created my own ngStyle directive that addresses this issue. Hopefully this is better than creating functions for every single scenario where you want to use ngStyle in this way.
app.directive("myStyle", function (){
return {
restrict: 'A',
link: function(scope, element, attrs)
{
var el = element[0],
attr = el.getAttribute('style');
el.setAttribute('style', attr);
// We need to watch for changes in the style in case required data is not yet ready when compiling
attrs.$observe('style', function (){
attr = el.getAttribute('style');
if(attr)
{
el.setAttribute('style', attr);
}
});
}
};
});
Then, you can use it this way:
<a my-style style="background-image: url('{{promise.myImage}}')"></a>
Upvotes: 5
Reputation: 65
Thx for your time! I solved the Problem with the input from Cherniv, but I'm not sure how. I changed the way I create the values. Now it's working.
$scope.calcCssShift = function(){
this.cssShift = ($scope.currentPosition * $scope.slideSize)*-1;
};
$scope.getCssShiftObject =function(){
return {'left':$scope.cssShift+'px'};
};
$scope.nextPosition = function(){
if((this.currentPosition+1) <= this.maxPosition){
$scope.currentPosition = this.currentPosition+1;
$scope.calcCssShift();
}
};
Upvotes: 1