Skip to content

Commit fa4b121

Browse files
committed
feat(ngModel): bind to getters/setters
Closes angular#768
1 parent ea820b5 commit fa4b121

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/ng/directive/input.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1807,7 +1807,12 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
18071807
ctrl.$modelValue = ctrl.$valid ? modelValue : undefined;
18081808
ctrl.$$invalidModelValue = ctrl.$valid ? undefined : modelValue;
18091809

1810-
ngModelSet($scope, ctrl.$modelValue);
1810+
var getter = ngModelGet($scope);
1811+
if (typeof getter === 'function') {
1812+
getter(ctrl.$modelValue);
1813+
} else {
1814+
ngModelSet($scope, ctrl.$modelValue);
1815+
}
18111816
forEach(ctrl.$viewChangeListeners, function(listener) {
18121817
try {
18131818
listener();
@@ -1883,6 +1888,10 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
18831888
$scope.$watch(function ngModelWatch() {
18841889
var modelValue = ngModelGet($scope);
18851890

1891+
if (typeof modelValue === 'function') {
1892+
modelValue = modelValue();
1893+
}
1894+
18861895
// if scope model value and ngModel value are out of sync
18871896
if (ctrl.$modelValue !== modelValue &&
18881897
(isUndefined(ctrl.$$invalidModelValue) || ctrl.$$invalidModelValue != modelValue)) {

test/ng/directive/inputSpec.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -654,6 +654,30 @@ describe('input', function() {
654654
});
655655

656656

657+
it('should bind to a getter', function() {
658+
compileInput('<input type="text" ng-model="name" name="alias" ng-change="change()" />');
659+
660+
scope.$apply(function() {
661+
scope.name = function () { return 'misko'; };
662+
});
663+
664+
expect(inputElm.val()).toBe('misko');
665+
});
666+
667+
668+
it('should bind to a setter', function() {
669+
compileInput('<input type="text" ng-model="name" name="alias" ng-change="change()" />');
670+
671+
var name = '';
672+
scope.name = function (newName) {
673+
return typeof newName !== 'undefined' ? (name = newName) : name;
674+
};
675+
changeInputValueTo('adam');
676+
expect(inputElm.val()).toBe('adam');
677+
expect(name).toBe('adam');
678+
});
679+
680+
657681
it('should not set readonly or disabled property on ie7', function() {
658682
this.addMatchers({
659683
toBeOff: function(attributeName) {

0 commit comments

Comments
 (0)