Seeking Solution:
Is there a way to develop an <input type="text">
field that contains a custom-formatted string serialization of an object and allows for bi-directional updates between the string and the model?
I am exploring AngularJS directives, but struggling to implement it successfully.
Detailed Inquiry:
Background
I have an object that serves as the core model for my application. It can be serialized into a specific format as follows:
It consists of 2-3 attributes, with their serializations joined by ";". If the third attribute is missing, no trailing ";" is included.
Attributes 2 and 3 are lists of objects, serialized by joining them with ",".
The serialization of the objects involves either a single string attribute or two concatenated with "x" in between.
I have a constructor that accepts a spec string, along with a toString
function, provided below for clarity:
World.prototype.toString = function() {
var spec = [];
spec[0] = this.version;
spec[1] = this.layers.map(function(layer) {
var c = (layer.c > 1) ? layer.c + 'x' : '';
return c + layer.id; //e.g. 'T' or '2xT'
}).join(',');
//spec[2] in python: ','.join(option.id for option in options if option.checked)
var options = this.options.filter(function(option) {
return option.checked;
});
if (options.length > 0)
spec[2] = options.map(function(option) {
return option.id;
}).join(',');
return spec.join(';');
};
The directive I attempted to use looks like this, but the $watch
only fires once:
angular.module('layersApp', []).directive('spec', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch('world', function(val) {
element.val(val.toString());
console.log('object updated', element.val());
}, true);
element.blur(function(e) {
scope.world = new World(element.val());
});
}
};
});
Main Question
What would be the best approach to achieve bi-directional binding in the following scenario?
<input type="text" data-ng-model="theWorld" spec>
Where spec
represents the custom directive mentioned above, facilitating two-way data flow.
Potential Solution
It would be beneficial to create a generic "serialization" directive for widespread use, similar to:
<input type="text" data-serialization="string2Foo, foo2String" data-ng-model="foo">
This directive would dynamically handle the object foo
, along with the functions string2Foo
and foo2String
for setting up customized serialization and deserialization processes.