牢骚
看了两天angular.js 基于ng与ngRoute试着写了个自动路由.请各路大神赐教...特别是eval这货.是否会引起安全问题...野路子js出身...不是啥都懂.请赐教.
这里只列出主要文件吧... 详情代码可见http://git.oschina.net/nmtuan/angular.js-autoRoute
代码
index.html
<!doctype html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="css/bootstrap.min.css"/>
</head>
<body>
<h1>angular autoRoute</h1>
<div ng-view></div>
<script src="lib/angular.min.js"></script>
<script src="lib/angular-route.min.js"></script>
<script src="js/myApp.js"></script>
</body>
</html>
myApp.js
//路由范围与检测
var routeRange = {
action: [],
dos: [],
//检测数组this[key]中是否包含val元素
check: function (key, val) {
var status = false;
for (var i in this[key]) {
if (this[key][i].indexOf(val) > -1) {
status = true;
}
}
return status;
},
//向this[key]中推入新元素val
set: function (action, dos) {
if (!this.check(this.action, action)) {
this.action.push(action);
}
if (!this.check(this.dos, dos)) {
this.dos.push(dos);
}
}
};
//错误页
var page404 = function ($scope) {
$scope.msg = '404 Not Found.!';
};
var myApp = angular.module('myApp', ['ngRoute']);
//ngRoute
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/:action/:dos', {
controller: ['$scope', '$routeParams', function ($scope, $routeParams) {
var action = $routeParams.action;
var dos = $routeParams.dos;
//检测action与dos是否已经在routeRange中定义
if (routeRange.check('action', action) && routeRange.check('dos', dos)) {
var dos = dos.replace(/(^|\s+)\w/g, function (s) {
return s.toUpperCase();
});
eval(action + dos + 'Ctrl($scope, $routeParams)');
} else {
page404($scope);
}
}],
templateUrl: function ($routeParams) {
var action = $routeParams.action;
var dos = $routeParams.dos;
if (routeRange.check('action', action) && routeRange.check('dos', dos)) {
return 'template/' + $routeParams.action + '/' + $routeParams.dos + '.html';
} else {
return 'template/page/404.html';
}
}
})
.otherwise({
redirectTo: '/index/index'
});
}]);
//example
routeRange.set('index', 'index');
var indexIndexCtrl = function ($scope, $routeParams) {
$scope.action = $routeParams.action;
$scope.dos = $routeParams.dos;
$scope.text = 'hello world.!';
};
俩模板文件
404.html
<div ng-controller="page404">
<h2>{{msg}}</h2>
</div>
index.html
<div ng-controller="indexIndexCtrl">
<h2>{{action + ' - ' + dos}}</h2>
<p><input type="text" ng-model="text"/></p>
<p>{{text}}</p>
</div>