Minas Minas
Minas Minas

Reputation: 91

change Background image in directive

i want to load an image as background in the directive. This should happen after an event. For example if the flag is true, the background should be changed.

How is it possible?

myApp.directive('imgDir', function () {
    return {
        restrict: 'A',
        scope: {
            updateMethod: '=',
        },
        link: function (scope, element, attrs) {

            this.changeBackground = function(flag){
              if(flag){
                var url = '/images/pic1.jpg'
                //load pic1 as background            
              }
              else{
                  var url = '/images/pic2.jpg'
                  //load pic2 as background
              }...
});

How does the html have to look like? Because the url is defined in the directive.

thx

Upvotes: 1

Views: 729

Answers (2)

morels
morels

Reputation: 2105

the HTML should be like

<div img-dir updateMethod="...">
   ...
</div>

,following the online official documentation. A directive restricted as attribute is written in the opening tag and if the scope specifies another attribute, it can be added inline.

Upvotes: 1

valepu
valepu

Reputation: 3315

If you just need to change image you can use ng-class and some css rules. https://docs.angularjs.org/api/ng/directive/ngClass

<div ng-class="{'img-1':flag, 'img-2':!flag}"></div>

and in your css

.img-1 {
    background-image: url('/images/pic1.jpg');
}


.img-2 {
    background-image: url('/images/pic2.jpg');
}

At a first glance i'm not even sure your directive would work. If you want to know more about directives and how to make one you should read this: https://docs.angularjs.org/guide/directive

Upvotes: 1

Related Questions