2017-04-01 30 views
0

我有一个自定义指令来在元素上应用背景图像,我希望它在范围更改上刷新UI。在范围更改后不刷新的指令

在阅读完后,我添加了$watch来观察范围变化,但我在ng-repeat中使用了指令,所以我不能将范围变量传递给它。

item.Url发生变化时,指令不刷新background-url。

我的指令:

.directive('bgImage', function() { 
     function applyBackgroundImage(element, url) { 
      if (!element || !url) { return; } 
      element.css({ 'background-image': ['url(', url, ')'].join('') }); 
     }; 

     return { 
      restrict: 'A', 
      link: function ($scope, element, attrs) { 
       if (!attrs.bgImage) { return; } 

       if ($scope.hasOwnProperty(attrs.bgImage)) { 
        $scope.$watch(attrs.bgImage, 
         function(newValue, oldValue) { 
          if (newValue == oldValue) { return; } 
          if (!newValue) { return; } 

          applyBackgroundImage(element, newValue); 
         }); 
       } else { 
        applyBackgroundImage(element, attrs.bgImage); 
       } 
      } 
     }; 
    }) 

用法:

<div class="item-box" ng-repeat="item in items"> 
    <div bg-image="{{item.PictureUrl}}"> 
    </div> 
</div> 
+0

我试图避免'风格= “背景图像:网址({{item.Url}})”' –

回答

1

也许这会有所帮助。

$scope.$watch(function() { 
    return attrs.bgImage 
    }, 
    function(newValue, oldValue) { 
     if (newValue == oldValue) { return; } 
     if (!newValue) { return; } 
     applyBackgroundImage(element, newValue); 
    }); 
+0

我不得不删除'如果(NEWVALUE ==属性oldValue){返回; ''但完美的作品 –