如果启用了间隔,我希望按钮或带有图标的链接,默认glyphicon-play
或glyphicon-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();
}
});
}
};
}]);
答案 0 :(得分:2)
使用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();
}
};
}
};
}]);