Io uso un servizio per creare un doppio senso di legame:.
angular.module('app').service('urlBinder', ['$location', function($location) {
this.bindOnScope = function(scope, name, urlParamName) {
// update the url when the scope variable changes
var unhookUrlUpdater = scope.$watch(name, function(newValue, oldValue) {
if (!angular.equals(oldValue, newValue)) {
$location.search(urlParamName, newValue);
}
});
// update the scope variable when the url changes
var unhookScopeUpdater = scope.$on('$locationChangeSuccess', function() {
var value = $location.search()[urlParamName];
if (!angular.equals(scope[name], value)) {
scope[name] = value;
}
});
// return a function to remove the hooks. Note that since these hooks are set up on the scope passed in, if that scope gets destroyed (e.g. because the user went to a different page and the controller is no longer present), then the hooks will be removed automatically.
return function() {
unhookUrlUpdater();
unhookScopeUpdater();
};
};
// the same thing but using getter/setter functions for when you want to bind to something not on the scope
this.bind = function(scope, getter, setter, urlParamName) {
var unhookUrlUpdater = scope.$watch(getter, function(newValue) {
$location.search(urlParamName, newValue);
});
var unhookScopeUpdater = scope.$on('$locationChangeSuccess', function() {
var value = $location.search()[urlParamName];
if (!angular.equals(getter(), value)) {
setter(value);
}
});
return function() {
unhookUrlUpdater();
unhookScopeUpdater();
};
};
}]);
nel controller:
angular.module('app').controller('ctrl', ['$scope', function($scope) {
// if binding to something on the scope:
urlBinder.bindToScope($scope, 'something', 'url-name');
$scope.something = 'test';
// or if the variable you want to bind isn't on the scope:
var someVariable;
urlBinder.bind(
$scope,
function() { return someVariable; },
function(value) { someVariable = value; },
'url-name');
}]);
È quindi possibile, ad esempio associare un ingresso alla url:
<div ng-controller="ctrl">
<input type="number" ng-model="something" />
</div>
Potrebbe anche essere necessario impostare reloadOnSearch : false
nel vostro percorso di configurazione, come non si vuole nell'ambito del controllore per essere distrutto e ricreato ogni volta che il ricerca po 'di cambiamenti url.
Mi piace! Si noti, tuttavia, che questo non è un collegamento dati bidirezionale. Quando viene chiamata la funzione, la variabile scope viene impostata sul valore corrente del parametro URL e, successivamente, il parametro URL viene aggiornato quando la variabile scope cambia. Se due ambiti si collegano allo stesso parametro URL, un ambito che lo modifica non aggiornerà la variabile nell'altro ambito. Questo è sufficiente per molti scopi però. – tobek
È vero, buon punto per quanto riguarda i diversi ambiti che si collegano allo stesso parametro URL. –