使用$ routeParams进行双向绑定?

Nic*_*ner 14 angularjs

使用ng-view和时$routeProvider,可以注入$routeParams以获取路径的值,例如/foo/:id/:user/:item.有没有办法在路径中设置这些参数?有点像$routeParams.id = 3,然后在网址中反映出来.

我知道这种效果可以通过实现$location.path(),但我希望更高级别的抽象不需要字符串操作.

Liv*_* T. 12

以下是我设法解决问题的方法.

控制器:

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);
  }]);
Run Code Online (Sandbox Code Playgroud)

模块声明+路由定义:

var app = angular.module('angularjs-starter', [], [
      '$routeProvider', '$locationProvider',
      function(routeProvider, locationProvider) {
        routeProvider.when('/main', {
          template : 'Main',
          controller : 'MainCtrl',
          reloadOnSearch : false
        });
      } ]);
Run Code Online (Sandbox Code Playgroud)

模板:

<body ng-controller="MainCtrl">
  <a href="#/main">No Params</a>
  <a href="#/main?param1=Hello&param2=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>
Run Code Online (Sandbox Code Playgroud)

演示:

参考文献: