Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

Allow ng-model bindings to arbitrary functions #1328

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/ng/directive/input.js
Expand Up @@ -995,7 +995,16 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$

// model -> value
var ctrl = this;
$scope.$watch(ngModelGet, function(value) {
var returnValue = ngModelGet(this, $scope);
var watcher = isFunction(returnValue)?
(function(self, locals){
return returnValue.call(self);
}):ngModelGet;
$scope.$watch(watcher, function(value) {

if (isFunction(value)) {
value = value();
}

// ignore change from view
if (ctrl.$modelValue === value) return;
Expand Down
11 changes: 10 additions & 1 deletion src/ng/parse.js
Expand Up @@ -646,13 +646,22 @@ function setter(obj, path, setValue) {
for (var i = 0; element.length > 1; i++) {
var key = element.shift();
var propertyObj = obj[key];
if (isFunction(propertyObj)) {
propertyObj = propertyObj();
}
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
}
obj[element.shift()] = setValue;
var key = element.shift();
if (isFunction(obj[key])) {
obj[key](setValue);
}
else {
obj[key] = setValue;
}
return setValue;
}

Expand Down
9 changes: 8 additions & 1 deletion test/ng/directive/inputSpec.js
Expand Up @@ -196,6 +196,14 @@ describe('NgModelController', function() {
expect(ctrl.$modelValue).toBe(10);
});

it('should set the value to $modelValue when value is a function', function() {
scope.$apply(function() {
scope.value = function() {
return 10;
};
});
expect(ctrl.$modelValue).toBe(10);
});

it('should pipeline all registered formatters in reversed order and set result to $viewValue',
function() {
Expand All @@ -218,7 +226,6 @@ describe('NgModelController', function() {
expect(ctrl.$viewValue).toBe('5');
});


it('should $render only if value changed', function() {
spyOn(ctrl, '$render');

Expand Down