Is there a way to easily convert a delimited string into an array of objects with data binding functionality?
ng-list
is suitable for arrays of strings. However, I have an array of objects where I want to delimit the text property for easy editing.
Works with Array of Strings:
$scope.arrayStrings = ["one", "two", "three"];
<textarea ng-model="arrayStrings" ng-list="
" ></textarea>
How can this be achieved with objects:
$scope.arrayObjects = [{
text: "one",
selected: true
}, {
text: "two",
selected: true
}, {
text: "three",
selected: true
}];
<textarea ng-model="arrayObjects" ng-list="
| text" ></textarea>
Check out the demo on plunker
One approach could be using ng-list on the array of strings and then mapping it to the array of objects. Then, use a $watch
to update the object array whenever the string array changes. However, this method may overwrite other properties on the object each time the array updates. (Demo in previous plunker revision)
$scope.$watch('arrayStrings', function() {
$scope.arrayObjects = $scope.arrayStrings.map(function(s){
return {
text: s,
selected: true
}
});
})
Update:
There seem to be issues when using ng-list
even with Krzysztof's suggestion:
toString: function() { return s }
Although overriding the toString
method helps initially display the set of objects, as soon as you start typing, ng-list
converts the objects back into an array of strings because toString
is not triggered at that point.
To clarify my objective, I want a list of editable objects with selectable titles. I aim to maintain selections even if titles change or new items are added.