0

Here is the directive. I think something is missing on my directive which can make it aware of the changes in the $scope.

'use strict';

 app.directive('backImg', function(){
        return function(scope, element, attrs) {
            var url = attrs.backImg;
            element.css({
                'background-image': 'url(' + url +')',
                'background-size' : 'cover'
            });
      };
 });

and here is the html

  <div back-img="{{url}}">
  </div>

in my controller, I have

$scope.url = 'image/placeholder.jpg';

Then I also have a button that changes value of $scope.url.

$scope.changeImage = function() {
    $scope.url = 'image/newimage.jpg';
}

I can see the changes in the DOM but the background image being displayed is still showing the old image which is placeholder.jpg. I noticed both urls are in the DOM after I called the changeImage() function.

<div back-img="http://localhost:9000/image/newimage.jpg" style="background-image: url(http://localhost:9000/image/placeholder.jpg); background-size: cover;">
</div>

1 Answer 1

1

I got it working! Woohoo! I'm learning directives!

app.directive('backImg', function() {
  return {
    restrict: 'A',
    link: function($scope, element, attrs) {
      $scope.$watch('url', function(n, o) {
        console.log('checking .....', n, o);
        if (n) {
          console.log('changing');
          element.css({
            'background-image': 'url(' + attrs.backImg + ')',
            'background-size': 'cover'
          });
        }
      });
    }
  };
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.