2013-09-30 16 views
2

我有一個angularjs的問題,甚至在研究後,我無法找到我錯在哪裏。Angular.js的ng樣式不會綁定值

我需要重新計算一個元素的「左」的CSS值。我使用'ng-style'指令和一個將返回一個帶有css值的對象的方法。那是 - afaik - 我必須做的。但是當我更新值時,它不會更新樣式。

納克綁定用法:

<div ng-style="getCssShiftObject()"> 

方法來創建對象

$scope.getCssShiftObject =function(){ 
    return {'left':this.cssShift+'px'}; 
}; 

方法來改變對象

$scope.nextPosition = function(){ 
    if((this.currentPosition+1) <= this.maxPosition){ 
     this.currentPosition = this.currentPosition+1; 
     this.cssShift = (this.currentPosition*this.slideSize)*-1; 
    } 
    return this.currentPosition; 
}; 

這將在內容在其他地方更新當我使用它這樣的:

{{getCssShiftObject()}}

我希望你能給麻省理工學院一擊,感謝您的時間!

+1

誰,當來電'$ scope.nextPosition'? – Cherniv

+0

你可以添加小提琴或蹦牀嗎? –

+0

通過ng-click指令調用 –

回答

1

Thx爲您的時間!我從切爾諾夫的輸入中解決了這個問題,但我不知道如何。我改變了創造價值的方式。現在它正在工作。

$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(); 
    } 
}; 
5

我碰到過類似的問題。我試圖使用ngStyle來加載背景圖片,但是如果表達式中的變量不是立即可用的(這可能是屬於資源承諾的一部分),它將無法工作。

爲了解決這個問題,我創建了自己的ngStyle指令來解決這個問題。希望這比爲每個想要以這種方式使用ngStyle的場景創建函數要好。

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); 
       } 
      }); 
     } 
    }; 
}); 

然後,您可以使用這種方式:

<a my-style style="background-image: url('{{promise.myImage}}')"></a> 
1

我曾與style屬性類似的問題。我的綁定在某些瀏覽器中不起作用,特別是IE。我使用ng-attr-style =「{{yourBindingExpression}}」解決了這個問題。

瞭解更多關於NG-ATTR插在https://docs.angularjs.org/guide/interpolation