在angularjs官方文档关于$routeProvider的配置中,对template和templateUrl的配置有这么一段话
if it is a function, it will be called with the following parameters:
{Array.<Object>} - route parameters extracted from the current$location.path() by applying the current route
读起来相当拗口,也不容易理解是什么意思。
简单来讲,template和temlateUrl的值可以是一个函数,它可以带参数,分别返回一个html脚本和一个html脚本文件的URL。不带参数的情况很简单,返回对应的数据就可以了。那带参数的情况呢,参数是什么?上面提到是route parameters(路由参数)。最开始的时候,以为是$routeParams,所以我们把$routeParams作为参数。其实在定义函数的时候,我们传递的参数其实是形参。那实参来自哪呢?这个函数其实是在后台执行的,由angularJS将实参传递给函数,当然为了引用实参,我们还是需要在函数中设置形参的。那实参是怎么来的呢?上文有提到当前route的$location.path()。在path配置片段中,有提到path参数如果使用命名组(named group)的话,它的参数会被提取存储在$routeParams。这个在path中被提取的参数就是我们这里的实参。
看代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body ng-app="Main">
<div ng-controller="MainController">
<div ng-view></div>
</div>
</body>
</html>
<script src="scripts/angular.min.js" type="text/javascript"></script>
<script src="scripts/angular-route.min.js" type="text/javascript"></script>
<script type="text/javascript">
function template(data)
{
console.log(data);
return '<span>`path`</span><br /><span>`url`</span>';
}
var app = angular.module('Main', ['ngRoute']);
app.controller('MainController', function ($scope, $location) {
$location.url('/test/1#?a=1#hash');
$scope.url = $location.url();
}).controller('controllor', function ($scope, $location, $route) {
$scope.path = $location.path();
});
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/test/:test', {
template: template,
controller: 'controllor'
});
}]);
</script>
执行后,可以在控制台输出{"test":"1"}。
上文中,还展示了作用域的问题($scope.url)。以及全局函数再angularjs的应用。
转载于:https://blog.51cto.com/tancfeng/1727699