如何摆脱jQuery的增生并以有角度的方式改进我当前的指令

How to get rid of jQuery accretions and improve my current directive in angular way?

本文关键字:方式改 指令 jQuery 何摆脱      更新时间:2023-09-26

如果启用了间隔,我希望有带图标的按钮或链接,默认为glyphicon-playglyphicon-pause。如何以更"有角度的方式"重构该指令,尤其是$element.hasClass("glyphicon-pause")$element.removeClass("glyphicon-pause").addClass("glyphicon-play");

<button play class="btn glyphicon glyphicon-play"></button>

当前指令:

app.directive('play', ['$interval', function ($interval) {
    return {
        restrict: 'A',
        link: function ($scope, $element, attrs) {
            var i = 0,
                interval;

            var play = function () {
                $interval.cancel(interval);
                interval = $interval(function () {
                    $scope.states[i].active = false;
                    $scope.states[i++].active = true;
                    i = i % 3;
                }, 1000);
            };

            var stop = function () {
                $interval.cancel(interval);
            };
            console.log($element, attrs);

            $element.on('click', function ($event) {
                if ($element.hasClass("glyphicon-pause")) {
                    $element.removeClass("glyphicon-pause").addClass("glyphicon-play");
                    stop();
                } else {
                    $element.removeClass("glyphicon-play").addClass("glyphicon-pause");
                    play();
                }
            });
        }
    };
}]);

使用ng-class和ng-click将是这里两个最有棱角的改进。

<button play class="btn glyphicon" ng-class="{glyphicon-play: isPlaying, glyphicon-pause: !isPlaying}" ng-click="togglePlay()"></button>

app.directive('play', ['$interval', function ($interval) {
    return {
        restrict: 'A',
        link: function ($scope, $element, attrs) {
            $scope.isPlaying = false;
            var i = 0,
                interval;
            var play = function () {
                $scope.isPlaying = true;
                $interval.cancel(interval);
                interval = $interval(function () {
                    $scope.states[i].active = false;
                    $scope.states[i++].active = true;
                    i = i % 3;
                }, 1000);
            };

            var stop = function () {
                $scope.isPlaying = false;
                $interval.cancel(interval);
            };
            console.log($element, attrs);
            $scope.togglePlay = function() {
              if($scope.isPlaying){
                stop();
              }else{
                play();
              }
            };
        }
    };
}]);