3

I have class named "tp-cont" which is loaded from a different .css file. I could change the background image using jQuery using the below code.

In HTML:

<li ng-click="changeTemplateBackgroundImage()"></li>

In Controller:

$scope.changeTemplateBackgroundImage = function(){

        var imageUrl = 'public/uploads/Admin/template_themes/1/black.png';
        $('.tp-cont').css('background-image','url(' + imageUrl + ')');

    };

I want to know if there a work around for the same using angularjs

Thanks is advance.

Answer given below:

In Controller :

$scope.changeTemplateBackgroundImage = function(){

        $scope.bgUrl = 'public/uploads/Admin/template_themes/1/black.png';

    };

In HTML :

<div class="tp-cont" ng-style="{ 'background-image': 'url({{bgUrl}})' }">
ajin
  • 1,136
  • 1
  • 11
  • 22

4 Answers4

4

In Controller :

$scope.changeTemplateBackgroundImage = function(){

        $scope.bgUrl = 'public/uploads/Admin/template_themes/1/black.png';

    };

In HTML :

<div class="tp-cont" ng-style="{ 'background-image': 'url({{bgUrl}})' }">
ajin
  • 1,136
  • 1
  • 11
  • 22
1

yes, you can create a directive and use the $element

https://docs.angularjs.org/api/ng/function/angular.element

you can also do this directly in your controller. It is alos possible to use vanile js with document.getElementById

Alexander_F
  • 2,831
  • 3
  • 28
  • 61
1

$scope.changeTemplateBackgroundImage = function(){

        var imageUrl = 'public/uploads/Admin/template_themes/1/black.png';
        var element = document.getElementByClassName("tp-cont");
        element.style.backgroundImage = 'url('+imageUrl')';

    };
Mahesh Nathwani
  • 121
  • 1
  • 9
1

You can use ng-style, like

<span ng-style="myStyle">Sample Text</span>, set the myStyle string in your function.

Mavlarn
  • 3,807
  • 2
  • 37
  • 57