Reputation: 6868
I have an array of objects which is created on a button click. Now I have a scope variable that is assigned a default value.
This scope variable is part of textbox so now when user updates the textbox value that value is not getting automatically updated in all the records in bonus
property of $scope.job.referrals
records.
Code:
$scope.job.defaultBonus = 65;
function addNewReferrals{
$scope.job.referrals.push({
id: null,
bonus: $scope.job.defaultBonus
});
}
Can anyone tell me why is this happening and how do I update all bonus
property in $scope.job.referrals
when the $scope.job.defaultBonus
gets change?
Upvotes: 0
Views: 31
Reputation: 23654
Listening for a change from an input field. You need ng-model
and ng-change
. ng-model
binds the input value to the scope object.
<input ng-model='job.defaultBonus' ng-change='addNewReferrals()' />
You can iterate the array with map()
and use the {...}
spread operator to update the record.
function addNewReferrals() {
$scope.job.referrals = $scope.job.referrals.map(el => ({ ...el,
bonus: $scope.job.defaultBonus
}))
}
I set up an object called $scope
for this snippet to demonstrate, but you would just use the angular property $scope
.
const $scope = {
job: {
defaultBonus: 0,
referrals: [{
id: 1,
name: "John"
},
{
id: 2,
name: "Fred"
},
{
id: 3,
name: "Mary"
}
]
}
}
$scope.job.defaultBonus = 65;
function addNewReferrals() {
$scope.job.referrals = $scope.job.referrals.map(el => ({ ...el,
bonus: $scope.job.defaultBonus
}))
}
addNewReferrals();
console.log($scope);
Upvotes: 1