当使用ng-view和$routeProvider时,可以注入$routeParams来获取路径的值,如/ foo /:id /:user /:item.有没有办法在路径中设置这些参数?像$routeParams.id = 3,然后反映在url.
我知道这个效果可以通过$location.path()来实现,但是我希望能够提供更高层次的抽象,不需要字符串操作.
这是我如何设法解决问题.
控制器:
app.controller('MainCtrl',[ '$scope','$log','$route','$routeParams','$location',function(scope,console,route,routeParams,location) { console.log('MainCtrl.create'); scope.route = route; scope.routeParams = routeParams; scope.location = location; //1. This needs to be enabled for each controller that needs to watch routeParams //2. I believe some encapsulation and reuse through a service might be a better way //3. The reference to routeParams will not change so we need to enable deep dirty checking,hence the third parameter scope.$watch('routeParams',function(newVal,oldVal) { angular.forEach(newVal,function(v,k) { location.search(k,v); }); },true); }]);
模块声明路线定义:
var app = angular.module('angularjs-starter',[],[ '$routeProvider','$locationProvider',function(routeProvider,locationProvider) { routeProvider.when('/main',{ template : 'Main',controller : 'MainCtrl',reloadOnSearch : false }); } ]);
模板:
<body ng-controller="MainCtrl"> <a href="#/main">No Params</a> <a href="#/main?param1=Hello¶m2=World!">With Params</a> <div ng-view></div> <p> <span>param1</span> <input type="text" ng-model="routeParams['param1']"> </p> <p> <span>param2</span> <input type="text" ng-model="routeParams['param2']"> </p> <pre>location.path() = {{location.path()}}</pre> <pre>routeParams = {{routeParams}}</pre> </body>
演示:
> plunker
参考文献: