【问题标题】:AngularJS + jQuery - Unable to hide / show element inside directiveAngularJS + jQuery - 无法隐藏/显示指令内的元素
【发布时间】:2013-04-11 22:40:25
【问题描述】:

我在网页上显示了一个元素 - 这个元素是一个 twitter 引导图标 -
<i class="icon-trash"></i>

当页面加载时,通过应用隐藏类的样式来隐藏图标:

.hidden {
    display: none;
}

现在,我创建了一个指令,其最简单的形式如下:

var app = angular.module('testApp', []);

app.directive('testDir', function() {
    return function(scope, iElement, iAttrs) {
        iElement.customMethod({
            source: function() {
                //Some other statements
                jQuery(".icon-trash").removeClass('hidden');
            }
        });
    };
});

该指令作为属性放置在输入框上。当用户输入输入文本时,指令函数确实被调用。但是,该图标不再显示,即即使调用了该函数(使用console.log() 检查),jQuery 代码似乎也没有删除隐藏类。知道为什么吗?

【问题讨论】:

  • 我认为你应该阅读stackoverflow.com/questions/14994391/… 并考虑使用 ng-class 而不是编写复杂的指令?
  • 试试$('.icon-trash').show();
  • .show() 将图标的display 属性设置为display: inline。实际显示属性应为display: inline-block,因此不会呈现图标。因此我需要添加和删除将显示none的类
  • 好的,然后试试$('icon-trash').attr('style', 'display: inline-block !important;')
  • 还有知道为什么 jQuery 不删除 hidden 类而是将这个样式属性添加到它吗?

标签: jquery angularjs


【解决方案1】:

解决方案 1: jQuery - .show() 和 .hide()。

隐藏在pageshow

$('.icon-trash').hide()

随时显示。

$('.icon-trash').show()

解决方案 2: 创建两个类,添加/删除它们。

.hide-me { display: none !important;}

.show-me { display: inline-block !important; }

$('.icon-trash').removeClass('hide-me').addClass('show-me');

解决方案 3:肮脏的直截了当的方式

$('.icon-trash').attr('style', 'display: inline-block !important;')

【讨论】:

  • 解决方案 #2 有效 - 这次我不必添加 !important
【解决方案2】:

此代码使用 ng-show 指令显示一个带有垃圾桶图标的按钮。每当字段 search 设置为某物时,即:用户在输入文本中输入了某物。否则,如果文本被删除,按钮将再次隐藏。

<input type="text" ng-model="search" />
<button class="btn" ng-show="search" ng-click="trash()">
    <i class="icon-trash"></i> button
</button>

当按钮被点击时,垃圾箱函数被调用。

app.controller('HomeController', ['$scope', function($scope) {
    $scope.search = undefined;

    $scope.trash = function() {
        console.log('clicked: trash button');
    };
}]);

【讨论】:

    【解决方案3】:

    也许它可以帮助隐藏/显示角度指令。在 html 中,必须在 angular 之前包含 Jquery,并且游览将按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多