Używam usługę stworzyć dwukierunkowa wiążące.
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();
};
};
}]);
W kontrolerze:
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');
}]);
następnie można na przykład powiązać wejście do adresu URL:
<div ng-controller="ctrl">
<input type="number" ng-model="something" />
</div>
Być może trzeba ustawić reloadOnSearch : false
w config trasy, jak nie chcesz zakres kontroler zostać zniszczone i odtworzone gdy wyszukiwania nieco zmienia URL.
Podoba mi się! Należy jednak pamiętać, że nie jest to dwukierunkowe wiązanie danych. Po wywołaniu funkcji zmienna zasięgu jest ustawiana na bieżącą wartość parametru URL, a następnie parametr adresu URL jest aktualizowany po zmianie zmiennej zasięgu. Jeśli dwa zakresy łączą się z tym samym parametrem URL, zmiana zakresu nie spowoduje aktualizacji zmiennej w innym zakresie. Jest to jednak wystarczające dla wielu celów. – tobek
To prawda, dobry punkt dotyczący różnych zasięgów powiązanych z tym samym parametrem URL. –