angularjs设置背景图像

时间:2016-03-06 15:08:46

标签: angularjs

我有一个div可视化进度。

因此我有这种ng风格的定义:

ng-style="{'background-image':'linear-gradient(left, rgba(255,0,0,1)'+bufferProgressPercent!=='NaN'?bufferProgressPercent:0+'%,rgba(0,0,0,0)'+(bufferProgressPercent!=='NaN'?bufferProgressPercent:0)+'%)!important'};"


//output in developer-tools
    <div class="audio-controls-wrapper" ng-style="{'backgroundImage':'linear-    gradient(left, rgba(255,0,0,1)'+bufferProgressPercent!=='NaN'?    bufferProgressPercent:0+'%,rgba(0,0,0,0)'+(bufferProgressPercent!=='NaN'?    bufferProgressPercent:0)+'%)'};">

该文档仅显示为明文。这些值不会被渲染。

值是正确的:

{{'background-image:linear-gradient(left, rgba(255,0,0,1)'+  (bufferProgressPercent!=='NaN'?bufferProgressPercent:0)+'%,rgba(0,0,0,0)'+(bufferProgressPercent!=='NaN'?bufferProgressPercent:0)+'%)'}}

给出了这个:

background-image:linear-gradient(left, rgba(255,0,0,1)59%,rgba(0,0,0,0)59%)

另一种尝试是创建一个指令:

<div class="audio-controls-wrapper" progress-animation="bufferProgressPercent" >

指令:

scope.$watch('progressAnimation', function(current, old){
    if(angular.isDefined(current) && current !== old){
      var backgroundImage = 'linear-gradient(left, rgba(255,0,0,1)'+   (current!=='NaN'?current:0)+'%,rgba(0,0,0,0)'+(current!=='NaN'?  current:0)+'%)!important';
      //scope.$applyAsync(function(){
        //element.css({'backgroundImage':backgroundImage});
        element[0].style.backgroundImage = backgroundImage;

       $compile(element.contents())(scope);
      //});
      console.log(backgroundImage)
      console.log(element[0].style)
    }
  });

但是从不设置此元素的属性backgroundImage。

2 个答案:

答案 0 :(得分:2)

您是否将监视功能输入指令?

例如

 .directive('progressAnimation', function () {
return {
    restrict: 'A', //E = element, A = attribute, C = class, M = comment         
    scope: { // input the var that you want to watch
            },

    link: function ($scope, element, attrs) { 
 //put your watch function here
          if(angular.isDefined(current) && current !== old){
          var backgroundImage = 'linear-gradient(left, rgba(255,0,0,1)'+   (current!=='NaN'?current:0)+'%,rgba(0,0,0,0)'+(current!=='NaN'?  current:0)+'%)!important';

         element[0].style.backgroundImage = backgroundImage;

           $compile(element.contents())(scope);

          console.log(backgroundImage)
          console.log(element[0].style)
        }

       } //DOM manipulation
}
});

答案 1 :(得分:0)

设置我必须使用的背景

background

而不是

background-image

进一步我不得不替换

linear-gradient(...

-moz-linear-gradient(

这意味着

{{'background-image:linear-gradient(left, rgba(255,0,0,1)'+  (bufferProgressPercent!=='NaN'?bufferProgressPercent:0)+'%,rgba(0,0,0,0)'+(bufferProgressPercent!=='NaN'?bufferProgressPercent:0)+'%)'}}

成了这个:

{{'background:-moz-linear-gradient((left, rgba(255,0,0,1)'+  (bufferProgressPercent!=='NaN'?bufferProgressPercent:0)+'%,rgba(0,0,0,0)'+(bufferProgressPercent!=='NaN'?bufferProgressPercent:0)+'%)'}}

我想我必须添加除了一定线性渐变之外的所有浏览器。