【问题标题】:How to use the child element's attrs in ngShow?如何在 ngShow 中使用子元素的属性?
【发布时间】:2015-07-13 03:45:00
【问题描述】:

我想检查一个元素的子元素在它的 ngShow 指令中是否有一个类名,比如

<div ng-show="check here if the child img has class name 'active'">
    <img class="...">
</div>

怎么做?

编辑

到目前为止,我所做的是为它编写一个类似的函数

<div ng-show="test(this)">....

<div ng-show="test($event)">....

当我将console.log 应用于test 函数中的这些参数时,我有一些对象我不明白它代表this 的含义,而我有undefined 代表$event,我知道我可以使用它在ng-click 但显然不在这里。

【问题讨论】:

  • 我们将不胜感激一些基本代码来展示您为解决这个问题所做的一些努力。
  • 你用什么给图像添加类名'active'?你不能在 ng-show 上使用相同的条件吗?
  • 正如 localhost 所说,最好能看到这个问题的更多上下文。 @BatuZet,查看How do I ask a good question? 的帮助页面(另外,localhost 是一个很棒的用户名)
  • 什么的孩子?我们没有水晶球。角度中的所有内容都取决于您的数据模型,而您没有显示任何内容。另外,您正在向后看,您希望数据中的属性触发active

标签: angularjs


【解决方案1】:

我认为值得看看“Thinking in AngularJS” if I have a jQuery background?

但是,为了回答您的问题,

  • 我创建了一个example PLNKR
    • 它回答了您的原始问题,然后您将其更改为检查元素的子元素是否具有该类。
    • 但是,同样的原则也适用,所以我将提供我的答案。
  • 值得注意的是,使用指令完成此操作可能是更好的做法。
  • 编辑:我还想支持@charlietfl 的评论。我认为您可能正在倒退。

话虽如此,这里有一个解决方案:

HTML

<!-- remove 'active' from class, and element is no longer shown -->
<div id="special" ng-show="showElem" class="active">ACTIVE</div>

JS(控制器)

// get the element we want to test
var elem = angular.element(document.querySelector('#special'));
// check if that element has the class 'active'
$scope.showElem = elem.hasClass('active');  // true or false

另一种方法是:

<div id="special" ng-show="elem.hasClass('active');" class="active">ACTIVE</div>

$scope.elem = angular.element(document.querySelector('#special'));

资源

【讨论】:

    猜你喜欢
    • 2014-11-08
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 2015-02-03
    • 2022-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多