1

I am using Angular.JS version 1.1.5 and I am using the following code I found on stackoverflow to change the background-image of a div:

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

Then, in my HTML, I have the following (jade template)

html(ng-app)
  div(ng-controller='myCtrl')
    div.big-image(ng-background='{{flags.imgSrc}}')

Now, please consider that flags.imgSrc does work and returns a correct image URL, as I have previously tested it with an img(ng-src='{{flags.imgSrc}}').

The problem with this is that it does not seem to work at all! I have tried to put a console.log('test') inside my directive but it does not seem to called. Any ideas why? Thanks in advance.

2 Answers 2

1

That is because you need to rename your directive to ngBackground Angular converts snake-case to camelCase for your convenience.

EXAMPLE:

.directive('ngBackground')

HTML

div.big-image(ng-background='{{flags.imgSrc}}')

Normal Example

App.directive('myAmazingDirective');

HTML

<div my-amazing-directive></div>

Also you would have to get your attributes using camelCase as well so.

var url = attrs.ngBackground;
Sign up to request clarification or add additional context in comments.

4 Comments

I cannot really see any convenience in that! thanks anyway! another thing, what about attrs['ng-background'] just inside the directive? should it be camelCased or snake-cased?
that's right maybe It's just that there's a bigger learning curve. Anyway, it still does not seem to work for me, any way to check it? I have added the console.log just before the return statement, is that correct? should it be called it everything was set right?
ok, got that. yea, the problem seems to be another one then... do you have 2 minutes in chat?
alright, got that. it seems to work if I insert the direct url, but it does not with something like ng-background="{{flags.imgSrc}}" which is pretty weird, it does with ng-src.... any idea why?
0

Your directive is likely never getting called. For a directive named "ng-background", I'm not even sure how you would call that. Normally the camel cased name of the directive is converted to the dashed name you use in your HTML.

To quote an example from AngularJS official documentation. They create a directive named myCurrentTime and call it via:

<span my-current-time="format"></span>

Look at the "Writing Directives (short version)" on this page: http://docs.angularjs.org/guide/directive

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.