title: Is there a canonical way to sync query params in the url (angular-ui-router) with variables on a scope with two-way binding?
body: <p>Here is an example implementation of what I mean:
  <a href="http://plnkr.co/edit/iwQPZfbDyKYwSzjjAPTN?p=preview" rel="nofollow">http://plnkr.co/edit/iwQPZfbDyKYwSzjjAPTN?p=preview</a></p>
  
  <p>Bound one way:</p>
  
  <ol>
  <li>Given you have the plunkr loaded with preview</li>
  <li>When you change the text in the bottom input containing only "fooDefault"</li>
  <li>Then you can see both query parameter in the url and the value on scope update all at</li>
  </ol>
  
  <p>And also the other way:</p>
  
  <ol>
  <li>Given you have the plunkr loaded with preview</li>
  <li>When you change the text in the top input containing "#/a?foo=fooDefault"</li>
  <li>Then you can see both query parameter in the url and the value on scope update all at once</li>
  </ol>
  
  <p>Most relevant code section (StackOverflow asked me to include one):</p>
  
  <pre><code>.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'})
  })
  </code></pre>
  
  <p>As you can see, I use 2 watchers to bind 'from url to scope' and also 'from scope to url'.</p>
  
  <p>But there is an issue with it:
  <a href="https://github.com/angular-ui/ui-router/issues/1840" rel="nofollow">https://github.com/angular-ui/ui-router/issues/1840</a></p>
  
  <p>Is there a better way for achieving the same kind of two-way binding without encountering that issue?</p>