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>
我試圖避免'風格= 「背景圖像:網址({{item.Url}})」' –