Can anyone offer the correct approach to this JSFiddle:
<style>
.red #btn{
background-color:red;
}
.blue #btn{
background-color:blue;
}
</style>
<body ng-app="ap" ng-controller="con">
<button id="btn" ng-click="changeClass()">Change Class</button>
</body>
<script>
var app = angular.module("ap",[]);
app.controller("con",function($scope){
$scope.class = "red";
$scope.changeClass = function(){
if ($scope.class === "red #btn")
$scope.class = "blue #btn";
else
$scope.class = "red #btn";
};
});
</script>
JsFiddle Link
I am trying to change the class of an element via .class & #ID.
Thanks in advance
Thanks tymeJV, new JSFiddle:
Solution
The toggling of the class can be done in 2 ways, i.e., either specifying the value to 0 or 1, depending upon the condition satisfied, by initially defining the value as 0, or depending on the boolean value, i.e., true or false, with satisfying the required condition, by initially setting the value as true.
Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.
ng-click is an attribute of an HTML element that can be used for the customized components in Angular. We use this attribute to detect if an element is clicked and tracks the mouse's cursor. ng-click takes a function as an attribute and calls it whenever an element is clicked.
The correct approach would be using ng-class
based on a toggle variable, consider:
CSS:
.red {
color: red;
}
JS:
$scope.toggle = false;
HTML:
<button id="btn" ng-click="toggle = !toggle" ng-class="{'red' : toggle}">Change Class</button>
ng-class
works by assigning the referenced class (in the above, "red") based on if the variable ("toggle") is true
or false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With