Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background Image in a Class using Angularjs

Tags:

html

angularjs

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}})' }">
like image 539
ajin Avatar asked May 10 '26 11:05

ajin


2 Answers

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}})' }">
like image 120
ajin Avatar answered May 13 '26 00:05

ajin


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

like image 36
Fribu - Smart Solutions Avatar answered May 13 '26 02:05

Fribu - Smart Solutions