I have an object exposing 2 properties (say foo
and bar
) via getters/setters in the form of method([value])
, so you can get their value by calling method()
and you can set their value by calling method(value)
.
Also, this object keeps foo
and bar
synchronized, in the way it makes bar
always to be 1 greater than foo
). This means whenever you set the value of foo
, it internally updates the value of bar
, and viceversa.
This is the sample implementation:
function obj() {
var foo = 1;
var bar = 2;
return {
foo: function (value) {
if (value) {
foo = value;
bar = foo + 1;
}
return foo;
},
bar: function (value) {
if (value) {
bar = value;
foo = bar - 1;
}
return bar;
}
}
}
Now I have two input
elements, one for each of these properties.
// in my controller
$scope.myobj = obj();
<!-- in the HTML -->
<input my-directive ng-model="myobj.foo">
<input my-directive ng-model="myobj.bar">
Please remember that foo
and bar
are functions, so I write a $formatter
to get the value by calling the getter; and a $parser
to set the value by calling the setter, like this:
.directive('myDirective', function () {
return {
require: 'ngModel',
link: function ($scope, $element, $attrs, ngModel) {
ngModel.$formatters.push(function (modelValue) {
return modelValue();
});
ngModel.$parsers.push(function (viewValue) {
ngModel.$modelValue(viewValue);
return ngModel.$modelValue;
});
}
};
});
You can check the example in jsFiddle or Plunker.
As you can see, the formatter/parser thing works just fine, but the problem is that the <input>
value of the property that is internally modified (say bar
if you changed foo
) is not updated.
I can't even grasp why in earth is not working. As you can see in the example, below each input I'm interpolating the same value which seems perfectly updated upon any change. Why ng-model isn't updating my <input>
value?