棱角分明.js ng 样式不会绑定值

Angular.js ng-style won't bind value

本文关键字:绑定 样式 ng js      更新时间:2023-09-26

我在angularjs方面遇到了问题,即使经过研究,我也找不到我错的地方。

我需要重新计算元素的 css 值"left"。我正在使用"ng-style"指令和一个将返回带有 css 值的对象的方法。那是 - afaik - 我必须做的。但是当我更新值时,它不会更新样式。

ng-bind 用法:

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

我希望你能给麻省理工学院一个打击,谢谢你的时间!

我遇到了类似的问题。我尝试使用 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>

感谢您的时间!我用切尔尼夫的输入解决了问题,但我不确定如何解决。我改变了创建值的方式。现在它正在工作。

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

我对样式属性也有类似的问题。我的绑定在某些浏览器中不起作用,尤其是 IE。我通过使用ng-attr-style="{{yourBindingExpression}}"解决了它。

阅读有关 ng-attr 插值的更多信息,请访问 https://docs.angularjs.org/guide/interpolation