Is there a recommended method for linking an input element to a specific field of an object in an array using its id?
I tried using ng-model
along with the find()
function from the array prototype. However, the implementation is not working properly as it only populates the input and throws an error at the beginning of page load:
Error: [ngModel:nonassign]
Snippet from AngularJS file:
$scope.myData = [{
"id": 51,
"state": "A"
},
{
"id": 52,
"state": "B"
},
{
"id": 53,
"state": "C"
},
{
"id": 54,
"state": "D"
}
];
$scope.bindObject = function(array, filterby, value, item) {
let foundObject = array.find(obj => obj[filterby] == value);
if (foundObject)
return foundObject[item];
else
return $scope.default;
}
Code snippet from HTML file:
<input type="text" ng-model="bindObject(myData, 'id', id_value, 'state')"></input>
Note: The value for
id_value
is fetched via a web request;
Are there any better or more elegant approaches to achieve this functionality?