Search code examples
angularjsangularjs-ng-clickng-classng-style

How can I apply ng-style dynamically if ng-class is true?


.test{color:red;background:blue;}
.test.selected {
position:relative;  left: 100px; padding:10px; background:green;
}

<div ng-style="myStyle" ng-class="{select: x.selected}" ng-click="select(x)" ng-repeat="x in myData" class="test"></div>


$scope.select = function (text) {   
    text.selected = true;
};

$scope.myStyle = {
    'color':'white',
    'font-weight':'bold'
}

When the div element has className "selected" by using condition true, how can I add 'myStyle' in ng-style as well. How to apply inline ng-style dynamically if ng-class condition is true? Here below I am able to see in debugger in inline with classNames added. Now I have the condition true and I can see the classname "selected" to it(class="test ng-scope selected"), All I want is an inline ng-style="myStyle" to be added when its true.

<div ng-class="{select: x.selected}" ng-click="select(x)" class="test ng-scope selected" ng-repeat="x in myData"> 

Solution

  • Try like to this.

    <div ng-style="x.selected && {'color':'white','font-weight':'bold'}"  
        ng-click="select(x)" ng-repeat="x in myData" ></div>
    

    Demo

    var app = angular.module('anApp', ['angular.filter']);
    app.controller('aCtrl', function($scope) {
      $scope.data = [
      {
        "id": 100,
        "value": "2452"
      },
      {
        "id": 100,
        "value": "2458"
      },
      {
        "id": 1,
        "value": "2457"
      },
      {
        "id": 1,
        "value": "2459"
      },
      {
        "id": 4,
        "value": "2460"
      },
      {
        "id": 5,
        "value": "3458"
      }
    ];
    
    $scope.select = function(x){
      x.selected = !x.selected;
    }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
      <script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
    <div ng-app="anApp" ng-controller="aCtrl">
    <div ng-style="x.selected && {'color':'red','font-weight':'bold'}"  
        ng-click="select(x)" ng-repeat="x in data" >
          {{x.value}}
        </div>
    
    </div>