admin管理员组

文章数量:1415414

I want to get the background color of a DIV element when I click on that div.

HTML -

<div style="background-color:red" ng-click="getFilter($event)" class="agenda col-md-4">ABCDEGF/div>

JS Controller -

$scope.getFilter = function(event){

};

If we do in in jQuery, It would have been done as -

$('div').click(function(){
   $color = $(this).css('background-color');
});

But I want to do with angularJs. Someone help ?

I want to get the background color of a DIV element when I click on that div.

HTML -

<div style="background-color:red" ng-click="getFilter($event)" class="agenda col-md-4">ABCDEGF/div>

JS Controller -

$scope.getFilter = function(event){

};

If we do in in jQuery, It would have been done as -

$('div').click(function(){
   $color = $(this).css('background-color');
});

But I want to do with angularJs. Someone help ?

Share Improve this question asked Jan 29, 2016 at 14:31 sajalsurajsajalsuraj 99217 silver badges34 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

you can use:

$scope.getFilter = function(event) {
    $scope.color = $(event.currentTarget).css('background-color');
};

You could use ng-style for setting color dynamically, I'd just have it inside the API response for each record. I assumed that you are rendering all the elements using ng-repeat directive.

Markup

<div ng-repeat="item in items" 
   ng-style="{'background-color': item.color}"
   ng-click="getFilter(item);" 
   class="agenda col-md-4">
      ABCDEGF
</div>

Code

$scope.getFilter = function(item){
    $color = item.color;
}

Created sample example with service to get and assign color dynamically. JSFiddle - https://jsfiddle/q16fcq99/ Modify the service with your required call. Hope this will help.

    <body ng-app="SampleApp">
      <div ng-controller="fcController">
        <div ng-style="{'background-color': divColor}" ng-click="getFilter($event);" class="agenda col-md-4">
          ABCDEGF
        </div>
      </div>
    </body>

        var sampleApp = angular.module("SampleApp", []);
    sampleApp.controller('fcController', function($scope, colorService) {
      $scope.divColor = 'red';
      $scope.getFilter = function(event) {
        $scope.divColor = colorService.getColor();
        console.log('Event Fired');
      };
    });
    sampleApp.service('colorService', function() {
      this.getColor = function() {
        return "blue"; //Call Actual Service to Get Color
      };
});

本文标签: javascriptGet the background color of divAngularJsStack Overflow