简体   繁体   中英

AngularJS, how to change fontawesome icon on click? (ng-click)

I'm trying to have a checkbox, so when you click on the default FontAwesome empty box ( fa-square-o ) it gets changed with this icon ( fa-check-square-o ).

How can I do that with AngularJS? I need to put a function in the controller and call it from ng-click ? What would be the correct function?

I found what I need in Jquery but would love to just use angular for it:

$("#checkBoxOn").click(function(event) {
$(this).find('i').toggleClass('fa-check-square-o');

If possible help me convert this in Angular!

Two parts:

  1. You need something that holds a boolean if something is checked. We can do that using an expression like this: ng-click="toggle = !toggle" . Basically, each time you click the element with that directive, toggle will become what it wasn't before.
  2. You can use a ternary operator to set the class: i ng-class="toggle ? 'fa-check-square-o' : 'square-o'"></i>

Together, this might become something like:

<span ng-click="toggle = !toggle">
   <i ng-class="toggle ? 'fa-check-square-o' : 'square-o'"></i>
   Some text with the toggle here, that is also clickable.
</span>

Based on your other question, to hide another element based on this, you can add ngHide to it:

<table ng-hide="toggle">

This question is similar to AngularJS toggle class using ng-class , but that does not answer the toggling portion.

Just to make it more interesting, you could do something with unicode instead if you don't want the extra dependencies. This uses ngShow and ngHide .

<span ng-click="toggle=!toggle">
  <span ng-show="toggle">&#9744;</span>
  <span ng-hide="toggle">&#9745;</span>
  Some text with the checkbox here
</span>

You need ngChecked .

When you change the checkbox, apply your method:

ng-checked="MyMethod()"

The most easiest example:

input type='checkbox' ng-checked='MyMethod()' />

Script:

$scope.MyMethod = function() {
  //your logic
  return true; //checked
}

You don't need to use jQuery, use ngClass , to change the classes according to what a variable holds

<checkbox ng-click="value = !value">
<span class="fa" ng-class="{'fa-square-o': !value , 'fa-check-square-o': value}"></span>

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