是否有一种规范的方法可以将 url(angular-ui-路由器)中的查询参数与具有双向绑定的范围内的变量同步?

Is there a canonical way to sync query params in the url (angular-ui-router) with variables on a scope with two-way binding?

这是我的意思的示例实现: http://plnkr.co/edit/iwQPZfbDyKYwSzjjAPTN?p=preview

绑定一种方式:

  1. 鉴于您已加载带有预览的 plunkr
  2. 当您更改仅包含 "fooDefault"
  3. 的底部输入中的文本时
  4. 然后你可以看到 url 中的查询参数和范围更新的值都在

反之亦然:

  1. 鉴于您已加载带有预览的 plunkr
  2. 当您更改顶部输入中包含“#/a?foo=fooDefault”的文本时
  3. 然后你可以看到 url 中的查询参数和作用域上的值同时更新

最相关的代码部分(Whosebug 要求我包括一个):

.factory('syncUrlWithScope', function ($location) {
  return function ($scope, defaultValues) {
    $scope.$watch(function () {
      return $location.search()
    }, function (newVal) {
      console.log(JSON.stringify(defaultValues), 'from url to scope', newVal)
      $scope.queryParams = newVal
    }, true)

    $scope.$watch('queryParams', function (newVal) {
      console.log(JSON.stringify(defaultValues), 'from scope to url', newVal, defaultValues)
      for (var key in defaultValues) if (defaultValues.hasOwnProperty(key)) {
        $scope.queryParams[key] = $scope.queryParams[key] || defaultValues[key]
      }
      $location.replace()
      $location.search($scope.queryParams)
    }, true)
  }
})
.controller('ctrl1', function ($scope, syncUrlWithScope) {
  syncUrlWithScope($scope, {foo: 'fooDefault'})
})
.controller('ctrl2', function ($scope, syncUrlWithScope) {
  syncUrlWithScope($scope, {bar: 'barDefault'})
})

如您所见,我使用了 2 个观察者来绑定 'from url to scope' 以及 'from scope to url'。

但是它有一个问题: https://github.com/angular-ui/ui-router/issues/1840

是否有更好的方法来实现相同类型的双向绑定而不会遇到该问题?

为了让我的视图对 js 端和手动通过 url 操作更改的搜索参数做出反应,我有类似的东西:

$scope.$on('$locationChangeSuccess', function () {
    console.log('$locationChangeSuccess LogsController');
    $scope.searchParams = parseSearchToTags($location.search());
    ... do something with params ...
});