How can I convert between a delimited string and an array of objects with data binding?
ng-list
will work with an array of strings. But I have an array of objects, in which I would like to delimit the text property so the text in the array can be editable.
Works with Array of Strings:
<!-- language: lang-js -->$scope.arrayStrings = ["one", "two", "three"];
<!-- language: lang-html -->
<textarea ng-model="arrayStrings" ng-list=" " ></textarea>
How can I get this to work with objects:
<!-- language: lang-js -->$scope.arrayObjects = [{
text: "one",
selected: true
}, {
text: "two",
selected: true
}, {
text: "three",
selected: true
}];
<!-- language: lang-html -->
<textarea ng-model="arrayObjects" ng-list=" | text" ></textarea>
Here's a demo in plunker
One possible idea I had was to use ng-list on the array of strings and then map that to the array of objects. The use a $watch
to update the object array anytime the string array changed. However, this still falls short because it will overwrite any other properties on the object every 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 still seem to be issues when using ng-list
even when using Krzysztof's suggestion:
toString: function() { return s }
Overriding the toString
method helps the set of objects when initially displayed, but as soon as you type anything, ng-list
converts the set of objects back into an array of strings because at that point toString
has not come into play.
To clarify what I'm trying to do. I really want a list of objects, with editable titles, that can also be selected. I'd like to preserve selections even when the title has changed or items have been added.