添加CSS类元素NG-点击 [英] Adding a CSS class to element on ng-click

查看:120
本文介绍了添加CSS类元素NG-点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的页面上的菜单项几个任意数字。简化的,就像这样。

I have several arbitrary number of menu items on my page. Simplified they look like this.

<a href="" class="menu-item" ng-click="...">...</a>

我想一个特定的类添加到正在单击以便其状态更改比别人的项目。

I would like to add a particular class to an item that is being clicked so that its state changes compared to others.

我知道我应该这样做sugin这样一个模式:

I know I should do it sugin this kind of a pattern:

<a href=""
   class="menu-item"
   ng-class="{ active: clicked }"
   ng-click="clicked = true">
...</a>

但问题是,我不能用单个变量,因为我有一个项目任意数量。我应该要么使用变量X数字或使用数组。但在任何情况下,我怎么会知道哪个项目与每个变量/数组索引去,除非我手动手工输入这些指标?

but the problem is that I can't use a single variable as I have an arbitrary number of items. I should either use X number of variables or use an array. But in any case how would I know which item goes with each variable/array index unless I manually enter those indices by hand?

我错过了,我可以在使用元素引用NG-点击,这样我就能元素本身上添加特定的类。但是,这将有所绑定 $范围和用户界面,即使我不会使用任何 $范围函数,将操纵UI。我做这一切的观点...

I'm missing element reference that I could use in ng-click so I could add a particular class on element itself. But that would somewhat bind $scope and UI even though I wouldn't be using any $scope function that would manipulate UI. I'd do it all in the view...

我应该怎么做呢?

推荐答案

这是解决这个问题的指令:

A directive that solves this problem:

app.directive("markable", function() {
    return {
        scope: {}, // create isolated scope, so as not to touch the parent
        template: "<a href='#' ng-click='mark()' ng-class='{ active: marked }'><span ng-transclude></span></a>",
        replace: true,
        transclude: true,
        link: function(scope, elem, attrs) {
            scope.marked = false;
            scope.mark = function() {
                scope.marked = true;
            };
        }
    };
});

使用它作为:

<a markable>Mark me</a>

相关小提琴: http://jsfiddle.net/9HP99/

一个指令的优点是,这是很容易使用。

The advantage of a directive is that it is very easy to use.

同样使用DOM-manupulating指令,通过角度的jQuery的杂交接口:

The same with a DOM-manupulating directive, through Angular's jQuery-ish interface:

app.directive("markable", function() {
    return {
        link: function(scope, elem, attrs) {
            elem.on("click", function() {
                elem.addClass("active");
            });
        }
    };
});

用法:

<a href="#" markable>Mark me</a>

小提琴: http://jsfiddle.net/atE4A/1/

这篇关于添加CSS类元素NG-点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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