Angular 点击时切换 属性 并在事件结束后重置

Angular toggle property on click and reset it when event has finished

我有两个播放按钮,需要在点击时切换它们的活动 class。曲目播放完毕后,我需要删除特定按钮的活动 class。

查看:

<div class="audio-player" ng-repeat="sample in audioCtrl.audioSamples">
    <button class="play-btn" ng-click="audioCtrl.play(sample.sampleId); toggle = !toggle" ng-class="{'active' : toggle}"></button>
</div>

控制器:

audioPlayer.onended = function () {
  // Can I set toggle false here somehow?
};

您需要做的就是将 'toggle' 变量添加到控制器(或直接添加到 $scope)。无论哪种方式都可以解决问题,但我建议将其添加到控制器中。你可以这样做...

控制器(假设'audioPlayer'是控制器'this'):

audioPlayer.toggle = false;

查看:

<div class="audio-player" ng-repeat="sample in audioCtrl.audioSamples">
    <button class="play-btn" ng-class="{'active' : audioCtrl.toggle}"
            ng-click="audioCtrl.play(sample.sampleId); audioCtrl.toggle = !audioCtrl.toggle">
    </button>
</div>

我提供了两种可以在特定相册上动态切换 class 的方法,我建议使用指令方法。但是当您发出 HTTP 请求时,另一个可能会更有帮助。

function exampleController($scope, $q, $timeout) {
  $scope.audioSamples = [{
      id: 1,
      name: "One"
    },
    {
      id: 2,
      name: "Two"
    },
    {
      id: 3,
      name: "Three"
    },
    {
      id: 4,
      name: "Four"
    }
  ];

  $scope.play = function(event) {
    var deferred = $q.defer();
    var elm = event.target;
    angular.element(elm).addClass("active");
    $timeout(function() {
      deferred.resolve(angular.element(elm).removeClass("active"));
      return deferred.promise;
    }, 5000);
  };
}

function exampleDirective() {
  return {
    restrict: "A",
    link: function(scope, element, attrs) {
      element.bind("click", function() {
        return element.hasClass("active") ?
          element.removeClass("active") :
          element.addClass("active");
      });
    }
  };
}

angular
  .module("app", [])
  .controller("exampleController", exampleController)
  .directive("exampleDirective", exampleDirective);
.container-fluid {
  background-color: #1D1F20;
  color: #fff;
  font-size: 14px;
  font-weight: bold;
  padding: 5% 10% 10% 10%;
  text-align: center;
}

.btn-container {
  display: inline;
}

.play-btn {
  margin: 10px;
  transition: all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}

.active {
  font-weight: bold;
  font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<link src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"></script>
<div class="container-fluid" ng-app="app">
  <div class="container" ng-controller="exampleController">
    <div class="btn-container" ng-repeat="sample in audioSamples">
      <button class="btn btn-primary play-btn" ng-click="play($event)" ng-bind="sample.name">
      </button>
    </div>
  </div>
</div>