【问题标题】:AngularJS selector like jQueryAngularJS 选择器,如 jQuery
【发布时间】:2017-08-28 16:22:35
【问题描述】:

我在 HTML 代码中有 3 个具有相同类的 div 元素:

<div class="hide">
</div>

<div class="hide">
</div>

<div class="hide">
</div>

在 jQuery 中,我可以在一个代码语句中隐藏所有 div:$(".hide").hide();。我们如何在angular js中隐藏单个代码语句中的所有div?

【问题讨论】:

  • 我已经用 ng-show/ng-hide 试过了,但是有没有其他方法,我可以只使用选择器并在 Angular JS 中隐藏 DOM 中的所有元素?
  • document.getElementsByTagName("body")[0].style.opacity = '0' 怎么样; ?
  • 在 Angular 中执行此操作的正确方法是 ng-show/ng-hide。

标签: jquery html angularjs jquery-selectors


【解决方案1】:

可以这样(混合AngularJS/jQuery):

var results = $document[0].getElementsByClassName("hide");
angular.forEach(results, function(result) {
    var wrappedResult = angular.element(result);
    wrappedResult.hide();
});

然而,将 jQuery 混合到 AngularJS 应用程序中通常是不受欢迎的,这看起来像是我不希望在生产应用程序中使用的非常脏的代码。

最佳方法“Angular”方式就是将多个&lt;div&gt;s 用外部&lt;div&gt; 包装并使用@987654325 @/ng-hide.

<div ng-hide="someTrueVariable">
    <div class="hide"></div>

    <div class="hide"></div>

    <div class="hide"></div>
</div>

如果您来自 jQuery 背景并正在转向 AngularJS,我会高度建议您查看以下 Stack Overflow 线程。我真的认为这将帮助您进入 AngularJS 开发思维模式: "Thinking in AngularJS" if I have a jQuery background?

【讨论】:

  • 因此,“可以”后面跟着“Angular”的方式来演示为什么在使用 AngularJS 时你不想像 jQuery 开发人员一样思考。
【解决方案2】:

将元素的类放入属性hide-element;

HTML:

<div hide-element="hide" class="hide">
    hide1
  </div>  
  <div hide-element="hide">
    hide2
  </div>
  <div hide-element="hide" class="hide">
    hide3
  </div>

JS:

使用hideElement属性获取类名并隐藏具有该类的元素

.directive('hideElement', function() {

    return {  
      restrict: 'A',
      scope: {
        hideElement: '@'
      },
      link: function(scope, ele, attr) {

        var className = scope.hideElement;
        ele.bind('click', function($event) {

          angular.element(document.querySelectorAll("." + className))
            .css('display', 'none');
        })
      }
    }
  })

工作demo plunker

【讨论】:

    猜你喜欢
    • 2014-11-19
    • 2019-11-28
    • 2013-08-11
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2019-05-21
    • 2010-11-16
    • 1970-01-01
    相关资源
    最近更新 更多