m.rufca
m.rufca

Reputation: 2678

Directive not refreshing after scope change

I have a custom directive to apply background-image on elements and I want it to refresh UI on scope changes.

After reading how to do it I added $watch to observe scope changes, but I was using the directive inside a ng-repeat so I cant pass a scope var to it.

When item.Url changes, the directive does not refresh background-url.

My directive:

.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);
                }
            }
        };
    })

Usage:

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

Upvotes: 0

Views: 44

Answers (1)

Gray Fox
Gray Fox

Reputation: 357

Probably this will help.

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

Upvotes: 1

Related Questions