<!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始终不走,而且没有任何报错,简直活见鬼