1

I need to toggle CSS style, based on ng-click event.

First time user click ng-click element the style will be applied, the second time click on ng-click element the CSS not changed as expected toggle.

Find working code below,

HTML:

<h1 ng-style="myObj" ng-click="change()">Welcome</h1>

JavaScript:

app.controller("myCtrl", function ($scope) {
    $scope.myObj = {
        "color": "white"
    }
    $scope.change = function () {
        $scope.myObj = {
            "color": "red"
        }
    }
});

I need to toggle CSS class based on ng-click.

Anyone guide me how to archive the same.

1
  • because your onchange event make it red and default is white use ng-class Commented Apr 4, 2016 at 9:44

2 Answers 2

4

You can use ng-class with a flag that'll be reverted on click.

/* Default class */
h1 {
  color: blue;
}
.red {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<h1 ng-app ng-class="{'red': flag}" ng-click="flag=!flag">Welcome</h1>

By default the flag will be undefined and thus falsey, so the class will not be applied. When clicked, flag = !flag will set the flag to true and the red class will be applied. On next click, the flag will be set to false and the red class will be removed.

Sign up to request clarification or add additional context in comments.

Comments

1

try this.

var app = angular.module('myApp', []);
app.controller("myCtrl", function($scope) {
  $scope.myObj = {
    "color" : "blue"}
$scope.change=function()
{
  $scope.myObj.color == 'red' ? $scope.myObj.color = 'blue' : $scope.myObj.color = 'red';
 
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl"><h1 ng-style="myObj" ng-click="change()">Welcome</h1>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.