To me it seems like the best solution is to use a directive; there's no need for the controller to know that the view is being updated. Javascript:
HTML:
CSS:
I have a fiddle that demonstrates. The idea is when a directive is clicked, a function is called on the directive that sets a variable to the current scope id. Then each directive also watches the same value. If the scope ID's match, then the current element is set to be active using ng-class. The reason to use directives, is that you no longer are dependent on a controller. In fact I don't have a controller at all (I do define a variable in the view named "model"). You can then reuse this directive anywhere in your project, not just on one controller. If you want to add some css or change css on a button click in angularjs,you need to use angular directive mg-class for this. It is very simple you just need to bind a variable into the directive mg-class and change it from the controller. Here is the HTML: <html ng-app="app"> <head> <title>Change on click</title> </head> <body ng-controller=Change> <div ng-class=Changecss>{{Changecss}}</div> <button ng-click="changeColor()>Change Color</button> <script type="text/javascript" src="js/angular.min.js"></script> <script type="text/javascript" src="js/example.js"></script>> </body> </html> Now below is the js code you need to add to your controller. var app = angular.module("app",[]); app.controller("Change",function($scope){ $scope.Changecss = green; $scope.changeColor = function(){ if ($scope.Changecss === green) $scope.Changecss = "blue"; else $scope.Changecss = green; }; }) Now you need to define class in your css. .green{ color:green; } .blue{ color:blue; } Many times we need to change the look and feel of an element in response to an event. Toggle classA class can be toggled using class binding in angular. <div [class.className] = “condition” /> Toggle class on clickFor toggling class on click event, associate the click event with a function in component class which will reverse the condition of class binding. Example, <div [class.visited] = “isVisited == true” bove example binds a class with the Associate a click event with this div so that when the div is clicked, it will invoke a function in component class. Thus, the function will be defined as public isVisited = false;public checkVisited() { When the component loads, This means that the condition of class binding( Thus, we have successfully toggled the class on click event. Hope you enjoyed reading the article. Original article can be found here |