2017-04-01 80 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){返回; ''但完美的作品 –

相關問題