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}})”' –