मैं एक सेवा का उपयोग बाध्यकारी एक दो तरह से बनाने के लिए:।
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();
};
};
}]);
अपने नियंत्रक में:
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');
}]);
फिर आप उदाहरण के लिए यूआरएल के लिए एक इनपुट बाध्य कर सकते हैं:
<div ng-controller="ctrl">
<input type="number" ng-model="something" />
</div>
तुम भी रूप में आप नियंत्रक गुंजाइश नष्ट हो नहीं करना चाहती और निर्मित, अपने मार्ग config में reloadOnSearch : false
स्थापित करने के लिए आवश्यकता हो सकती है जब भी यूआरएल परिवर्तन की खोज बिट।
मुझे यह पसंद है! नोट, हालांकि, यह वास्तव में दो-तरफा डाटाबेसिंग नहीं है। जब फ़ंक्शन को कॉल किया जाता है, तो स्कोप वैरिएबल URL param के वर्तमान मान पर सेट होता है, और उसके बाद, URL चरम को बदलता है जब स्कोप परिवर्तनीय परिवर्तन होते हैं। यदि दो स्कॉप्स एक ही यूआरएल परम से जुड़ते हैं, तो इसे बदलने वाला एक गुंजाइश दूसरे दायरे में चर को अपडेट नहीं करेगा। हालांकि यह कई उद्देश्यों के लिए पर्याप्त है। – tobek
यह वही सही है, एक ही यूआरएल परम के लिए बाध्यकारी विभिन्न क्षेत्रों के बारे में अच्छा बिंदु। –