<!DOCTYPE html>
<html>
<head>
<title>基于AngularJS前端路由的圖檔顯示控件</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Cache" content="no-cache">
<style>
body{
width: 800px;
height: 480px;
margin: 0;
padding: 0;
}
#contentview{
width: 100%;
height: 100%;
}
#contentview #current_img{
width: 100%; /* or any custom size */
height: 100%;
max-height: 100%;
max-width: 100%;
object-fit: contain;
object-position: 0 0;
}
</style>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="angular-1.0.8.js"></script>
<!--script type="text/javascript" src="angular.min.js"></script-->
<script>
var imgUrls = [ //圖檔url清單;
"1.jpg",
"2.jpg",
"3.jpg",
"4.jpg"
];
</script>
</head>
<body style="background: black;" ng-app="myApp" ng-controller="ImageViewerCtrl">
<div ng-view id="contentview">
<!-- image viewer controller's content -->
<!--img id="current_img" src="{{$parent.imgUrls[$parent.imgId]}}" ng-cloak /-->
</div>
<script type="text/javascript">
window.onerror = function(e){
console.log(e);
}
var myAppModule = angular.module('myApp', []);
myAppModule.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/image/:id', {
template: '<img id="current_img" src="{{imgUrls[imgId]}}" ng-click="gotoNextImage()" img-autosize0 />',
//templateUrl: '/partials/image-viewer.tpl.html',
controller: 'ImageViewerCtrl'
})
.otherwise({redirectTo: '/image/0'}); //在浏覽器強制重新整理的情況下,還是會先加載/image/0(雖然沒有顯示出來)
}]);
myAppModule.controller('ImageViewerCtrl', function($scope, $location, $timeout, $route, $routeParams){
$scope.angular = angular; //exposed;
$scope.imgUrls = imgUrls;
console.log("$routeParams="+ JSON.stringify($routeParams));
$scope.imgId = $routeParams.id || 0; //undefined? why?
console.log("$scope.imgId="+$scope.imgId);
/*
$timeout(function() {
console.log("try to call $location.path");
$location.path("/image/0");
}, 2000);
*/
$scope.gotoNextImage = function(){
var nextImgId;
if(Number($scope.imgId)<$scope.imgUrls.length-1)
nextImgId = Number($scope.imgId) + 1;
else
nextImgId = 0;
$location.path("/image/"+nextImgId);
}
});
myAppModule.directive("imgAutosize", function(){
return {
restrict: 'EA',
compile: function(element, attrs) {
$(element).on("load", function(){
var width = $(element.parentNode).width();
var height = $(element.parentNode).height();
$(element).css({
width: "100%",
height: 'auto'
})
});
}
};
})
</script>
<footer>angular.version.full: {{angular.version.full}}</footer>
</body>
</html>
初學者障礙:一開始配置route path的時候,使用了相對路徑,而不是絕對路徑(/開始),導緻指定的controller始終不走,而且沒有任何報錯,簡直活見鬼