简体   繁体   中英

ng-click to undo event AngularJs

The idea is to create a checklist. When the user clicks on a circle it changes its background color. If he clicks it again it should reset the color.

在此处输入图片说明

I managed to change the background to green when the user checks his progress like this:

<i class="circle1" 
   ng-style="myStyle1" 
   ng-click="myStyle1={'background-color':'green'}">1</i>

Now my problem is how to reset the color to white when the user clicks again?

Thank you for your help.

One option would be to introduce a css class which is toggled when you click the element. You can do this with a combination of ng-class and using ng-click to toggle a variable.

<i class="circle1" ng-class="{'green-circle': isToggled === true}" ng-click="isToggled = !isToggled">1 - {{isToggled}}</i>

 angular.module("app", []); 
 .circle1 { background: red; } .green-circle { background: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app"> <i class="circle1" ng-class="{'green-circle': isToggled === true}" ng-click="isToggled = !isToggled">1 - {{isToggled}}</i> </div> 

The downfall of this solution is that you would need a different isToggled variable for each circle. A better and more re-usable solution would be to create a directive that handles this:

 var app = angular.module("app", []); app.directive('toggleClass', function() { return { restrict: 'A', link: function(scope, element, attrs) { element.on('click', function() { element.toggleClass(attrs.toggleClass); }); } }; }); 
 .circle1 { background: red; } .green-circle { background: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app"> <i class="circle1" toggle-class="green-circle">One</i> <i class="circle1" toggle-class="green-circle">Two</i> <i class="circle1" toggle-class="green-circle">Three</i> </div> 

Why don't you follow this algorithm and write some code,

  1. write a common function to reset color

  2. Call that function via ng-click and get currently clicked element

  3. and reset color of that elements plus all elements next to it by changing it's class

Remember resetting color of all nodes next to current code is must, else it will not look like Progress . It will just look like on-off buttons

You can post code again if you are getting some errors

HTML

 <i class="circle1" id ="circle1" ng-click="changeColor()">1</i>

JS code:

$scope.changeColor= function() {
    var i=0
    if(i%2 ==0)
    {
    document.getElementbyID('circle1').style.background ="original color"
    }
    else
    {
    document.getElementbyID('circle1').style.background ="green"
    }
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM