[英]Toggle elements in sequence - show one, then hide it and show the next
假設我們有10盞燈( we use li tag
)。 我想通過一個這樣向他們展示一個:
<h3>Light</h3>
<div ng-app ng-controller="MyCtrl">
<ul>
<li class="dot">
</li>
<li class="dot">
</li>
<li class="dot">
</li>
<li class="dot">
</li>
<li class="dot">
</li>
<li class="dot">
</li>
<li class="dot">
</li>
</ul>
</div>
第一盞燈=亮
其余主題=關閉。
之后
第二盞燈=開
第一盞和其他燈熄滅
我怎樣才能做到這一點?
小提琴: http : //jsfiddle.net/RkykR/1237/
第一個示例在每次單擊按鈕時手動切換元素。
<div ng-app="myApp" ng-controller="MyCtrl">
<button ng-click="switch()">Switch</button>
<ul>
<li class="item" ng-class="{on: $index === selectedIdx}" class="item" ng-repeat="item in items track by $index"></li>
</ul>
</div>
.item {
background:red;
width:5px;
height:5px;
list-style:none;
margin-bottom:5px;
visibility: hidden;
}
.on {
visibility: visible;
}
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
// make array with 10 items
$scope.items = new Array(10);
$scope.selectedIdx = 0;
$scope.switch = function() {
++$scope.selectedIdx;
if ($scope.selectedIdx === $scope.items.length) {
$scope.selectedIdx = 0;
}
};
})
;
這是另一個版本,燈光會自動移動,可以通過實時演示按鈕(單擊此處)停止和重新啟動:
<div ng-app="myApp" ng-controller="MyCtrl">
<button ng-click="switch()">{{timer ? 'Stop' : 'Start'}}</button>
<ul>
<li class="item" ng-class="{on: $index === selectedIdx}" class="item" ng-repeat="item in items track by $index"></li>
</ul>
</div>
angular.module('myApp', [])
.controller('MyCtrl', function($scope, $interval) {
// make array with 10 items
$scope.items = new Array(10);
$scope.selectedIdx = null;
$scope.timer = null;
$scope.switch = function() {
$scope.timer ? stop() : start();
};
function stop() {
$interval.cancel($scope.timer);
$scope.timer = null;
}
function start() {
$scope.timer = $interval(function() {
$scope.selectedIdx = $scope.selectedIdx === null ? 0 : $scope.selectedIdx+1;
if ($scope.selectedIdx === $scope.items.length) {
$scope.selectedIdx = 0;
}
}, 500);
}
start();
})
;
您可以使用$timeout
延遲點亮點。 如您所見,我使用遞歸函數來執行...
CONTROLLER
function MyCtrl($scope, $timeout) {
$scope.lights = [0,1,2,3,4,5,6];
$scope.currentLight = 0;
function light(index){
if($scope.lights.length < index) {
light(0);
} else {
$scope.currentLight = index;
$timeout(function(){
light(++index);
}, 1000);
}
}
light(0);
}
HTML
<h3>Light</h3>
<div ng-app ng-controller="MyCtrl">
<ul ng-repeat="light in lights">
<li class="dot" ng-class="{'red': $index == currentLight}">
</li>
</ul>
</div>
實際上,這必須是您在課堂上要做的一個小型開發練習。 因此,我通常不會回答此類問題。 但是,由於我心情愉快,所以我只更新了您的JSFiddle。
但是,請盡力自行解決。 有1000種方法可以實現此目的。 但是下面是一個簡單的答案。
function MyCtrl($scope) {
$scope.activeLight = 3;
$scope.data = [1,2,3,4,5,6,7];
$scope.update = function(index) {
$scope.activeLight = index;
};
單擊此處獲取更新的小提琴 <<請在單擊之前嘗試一下:)只是一個友好的建議。 另外,嘗試一下並添加計時器以自動運行它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.