angularJS實戰之小案例--隨機抽獎
阿新 • • 發佈:2018-12-23
cssangular.module("lottery",[]) .controller('ctrl_lottery',['$scope','$timeout',function($scope,$timeout){ //1.初始化獎品資料 $scope.items = [ {id:1,name:"歐洲豪華遊",status:0}, {id:2,name:"Mac臺式電腦",status:0}, {id:3,name:"IPhone6手機",status:0}, {id:4,name:"時尚山地車",status:0}, {id:5,name:"高清數字電視",status:0}, {id:6,name:"100元話費",status:0} ]; $scope.result = "獎品為空"; $scope.$$ = function(id){ return document.getElementById(id); } $scope.showhide = function(pre,next){ pre = "step"+pre; next = "step"+next; $scope.$$(pre).style.display = "none"; $scope.$$(next).style.display = "block"; } //開始抽獎 $scope.start = function(){ $scope.showhide(1,2); //step1隱藏 step2顯示 var circle = 5; var selkey = Math.floor(Math.random()*$scope.items.length); var next = function(key){ $scope.items[key].status = true; //該獎品顯示active狀態 ng-class="{'active':item.status}" if((key-1)>=0){ $scope.items[key-1].status = false; //前一個獎品removeClass active } if(key==0){ $scope.items[$scope.items.length-1].status = false; } var timer = $timeout(function() { if(circle <= 0 && selkey == key){ //完成指定圈數&&隨機中獎數值與某個獎品的索引號一致 $scope.showhide(2,3); //切換到顯示獎品頁面 $scope.result = $scope.items[key].name; return; } if($scope.items.length == key+1){ circle--; //一圈結束 } if($scope.items[key+1]){ next(key+1); //迴圈呼叫next() 下一個獎品active }else{ next(0); //一圈結束,從頭開始 } }, 100); } next(0); //首次執行next() } //顯示獎品時 $scope.reset = function(){ $scope.showhide(3,1); //隱藏 step3 顯示step1 } $scope.edit = function(){ $scope.showhide(3,4); } //修改獎品時 $scope.add =function(){ var last_id = lastid(); $scope.items.push({id:last_id,name:$scope.name,status:0}); } $scope.del =function(id){ angular.forEach($scope.items,function(value,key){ if(id == value.id){ $scope.items.splice(key,1); }; }) } $scope.return = function(){ $scope.showhide(4,3); } //內部函式,獲取最後一項資料的id號 function lastid(){ var id = 0; angular.forEach($scope.items,function(value,key){ if(id<value.id){ id = value.id; } }) return ++id; //最後一個元素id加1 } }])