Angular.js 如何在单击时更改元素 css 类并删除所有其他元素 [英] Angular.js How to change an elements css class on click and to remove all others

查看:26
本文介绍了Angular.js 如何在单击时更改元素 css 类并删除所有其他元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使我的两个元素切换,因此如果单击一个元素,它将删除 my-class 的所有引用并将其应用于其自身.有什么想法吗?

<span id="1" ng-style="my-class" ng-click="tog=my-class"></span><span id="2" ng-style="my-class" ng-click="tog=my-class"></span>

干杯!

解决方案

创建一个名为 selectedIndex 的范围属性和一个 itemClicked 函数:

function MyController ($scope) {$scope.collection = ["项目 1", "项目 2"];$scope.selectedIndex = 0;//无论默认选择的索引是什么,使用 -1 表示不选择$scope.itemClicked = 函数($index){$scope.selectedIndex = $index;};}

然后我的模板看起来像这样:

<span ng-repeat="集合中的项目"ng-class="{'selected-class-name': $index == selectedIndex }"ng-click="itemClicked($index)">{{ item }} </span>

仅供参考 $index 是 ng-repeat 指令中可用的魔法变量.

您也可以在指令和模板中使用相同的示例.

这是一个有效的 plnkr:

http://plnkr.co/edit/jOO8YdPiSJEaOcayEP1X?p=preview

i'm trying to make my two elements toggle, so if one element is clicked it will remove all references of my-class and apply it to its self. Any ideas?

<span id="1" ng-style="my-class" ng-click="tog=my-class"></span>

<span id="2" ng-style="my-class" ng-click="tog=my-class"></span>

Cheers!

解决方案

Create a scope property called selectedIndex, and an itemClicked function:

function MyController ($scope) {
  $scope.collection = ["Item 1", "Item 2"];

  $scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection

  $scope.itemClicked = function ($index) {
    $scope.selectedIndex = $index;
  };
}

Then my template would look something like this:

<div>
      <span ng-repeat="item in collection"
             ng-class="{ 'selected-class-name': $index == selectedIndex }"
             ng-click="itemClicked($index)"> {{ item }} </span>
</div>

Just for reference $index is a magic variable available within ng-repeat directives.

You can use this same sample within a directive and template as well.

Here is a working plnkr:

http://plnkr.co/edit/jOO8YdPiSJEaOcayEP1X?p=preview

这篇关于Angular.js 如何在单击时更改元素 css 类并删除所有其他元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆