【问题标题】:AngularJS - Add Class to Child ElementAngularJS - 向子元素添加类
【发布时间】:2017-10-29 22:54:52
【问题描述】:

我有一个按钮,如 example.html 中所示,它位于 ng-repeat 指令中。因此,还有很多类似的。 如何在调用syncAccount() 时将fa-spin 类添加到子i 元素,然后从pullProfile() 末尾的同一子元素中删除fa-spin 类?强>

-----example.html

<md-button class="md-raised md-default" ng-click="syncAccount(account.username)">
    <i class="fal fa-sync"></i> Re-sync
</md-button>

-----example.controller.js

$scope.syncAccount = function(username)
{
    console.log('syncing ' + username + ' ...')
    $scope.pullProfile(username)
}

$scope.pullProfile = function(username)
{
    // do stuff
    // remove the fa-spin class
}

我尝试使用angular.element().closest() 没有成功。示例:

-----example.html

<md-button class="md-raised md-default" ng-click="syncAccount($event, account.username)">
    <i class="fal fa-sync"></i> Re-sync
</md-button>

-----example.controller.js

(已更新以反映 chiliNUT 在 cmets 中建议的解决方案)

$scope.syncAccount = function($event, username)
{
    var spinElement = angular.element($event.currentTarget).find('.fa-sync')
    spinElement.addClass('fa-spin')

    console.log('syncing ' + username + ' ...')
    $scope.pullProfile(spinElement, username)
}

$scope.pullProfile = function(spinElement, username)
{
    // do stuff
    spinElement.removeClass('fa-spin')
}

旁白:

使用.find('i') 不起作用,因为.find() 仅限于按标签名称查找。见这里:https://docs.angularjs.org/api/ng/function/angular.element

【问题讨论】:

  • closest 不是这样工作的。而不是.closest('i') 尝试.find('i')
  • 在我的示例中,.find('i') 没有返回任何内容。 .find('.fa-sync') 虽然有效,但效果相同。如果您发布为答案,我会将其标记为已接受。谢谢。
  • 请不要在 Angular 中使用基于 jQuery 的解决方案。这是一种非常糟糕的时尚。
  • angular.element().find() 是 AngularJS 的 jqLit​​e 的一个函数,不需要明确的 jQuery。由于 jqLit​​e 已经是 Angular 的一部分,我认为没有理由不能在这里使用它。

标签: javascript angularjs


【解决方案1】:

试试这个

<md-button class="md-raised md-default" ng-click="syncAccount($event, account.username)">
    <i class="fa {{ syncInProgress ? 'fa-spin' : 'fa-sync' }} "></i> Re-sync
</md-button>

在控制器中

$scope.syncInProgress = false;
$scope.syncAccount = function(index) {
    $scope.syncInProgress = true;
};

同步后请将syncInProgress的值更改为false

【讨论】:

  • 谢谢,但是按钮位于 ng-repeat 指令中,因此,许多按钮存在于一个视图中。我相信这会通过使用单个布尔变量 $scope.syncInProgress 导致冲突。
猜你喜欢
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多