I have an object that displays 2 properties (say foo and bar ) via getters / seters in the form of method([value]) , so you can get their value by calling method() , and you can set their value to the method(value)
In addition, this object supports synchronization of foo and bar , since its bar will always be 1 more than foo ). This means that whenever you set the value to foo , it internally updates the value of bar and vice versa.
This is an example 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(); <input my-directive ng-model="myobj.foo"> <input my-directive ng-model="myobj.bar">
Remember that foo and bar are functions, so I write $formatter to get the value by calling getter; and a $parser to set the value by calling the setter, for example:
.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 formatting / parser thing works fine, but the problem is that the <input> value of the property, which is internally modified (e.g. bar , if you changed foo ) is not updated .
I canβt even understand why itβs not working on earth. As you can see in the example, under each input, I interpolate the same value, which seems completely updated with any changes. Why doesn't the ng model update the <input> value?