简体   繁体   English

AngularJS,如何更改单击时的字体图标? (NG-点击)

[英]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 ). 我正在尝试一个复选框,所以当您单击默认的FontAwesome空框( fa-square-o )时,此图标( fa-check-square-o )发生了变化。

How can I do that with AngularJS? 如何使用AngularJS做到这一点? I need to put a function in the controller and call it from ng-click ? 我需要在控制器中放置一个函数,然后从ng-click调用它? What would be the correct function? 正确的功能是什么?

I found what I need in Jquery but would love to just use angular for it: 我在Jquery中找到了我需要的东西,但只想使用angular:

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

If possible help me convert this in Angular! 如果可能的话,请帮我将其转换为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" . 我们可以使用这样的表达式来做到这一点: ng-click="toggle = !toggle" Basically, each time you click the element with that directive, toggle will become what it wasn't before. 基本上,每次您使用该指令单击元素时,toggle都会变成以前没有的状态。
  2. You can use a ternary operator to set the class: i ng-class="toggle ? 'fa-check-square-o' : 'square-o'"></i> 您可以使用三元运算符设置类: 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: 根据您的其他问题,要隐藏基于此的另一个元素,可以向其添加ngHide

<table ng-hide="toggle">

This question is similar to AngularJS toggle class using ng-class , but that does not answer the toggling portion. 这个问题类似于使用ng-class的AngularJS切换类 ,但是不能回答切换部分。

Just to make it more interesting, you could do something with unicode instead if you don't want the extra dependencies. 只是为了使其更有趣,如果您不希望额外的依赖项,可以使用unicode代替。 This uses ngShow and ngHide . 这使用ngShowngHide

<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 . 您需要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 您不需要使用jQuery,可以使用ngClass来根据变量保存的内容更改类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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