当范围变量中的值发生变化时,数据未在对象数组中更新
Data not getting updated in array of objects when the value in scope variable changes
我有一个对象数组,它是在单击按钮时创建的。现在我有一个分配了默认值的范围变量。
此范围变量是文本框的一部分,因此现在当用户更新文本框值时,该值不会在 bonus
属性 中的所有记录中自动更新 $scope.job.referrals
记录。
代码:
$scope.job.defaultBonus = 65;
function addNewReferrals{
$scope.job.referrals.push({
id: null,
bonus: $scope.job.defaultBonus
});
}
谁能告诉我为什么会这样,当 $scope.job.defaultBonus
发生变化时,我该如何更新 $scope.job.referrals
中的所有 bonus
属性?
正在侦听输入字段的更改。您需要 ng-model
和 ng-change
。 ng-model
将输入值绑定到范围对象。
<input ng-model='job.defaultBonus' ng-change='addNewReferrals()' />
您可以使用 map()
迭代数组并使用 {...}
展开运算符来更新记录。
function addNewReferrals() {
$scope.job.referrals = $scope.job.referrals.map(el => ({ ...el,
bonus: $scope.job.defaultBonus
}))
}
我为这个片段设置了一个名为 $scope
的对象来演示,但您只需使用 angular 属性 $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);
我有一个对象数组,它是在单击按钮时创建的。现在我有一个分配了默认值的范围变量。
此范围变量是文本框的一部分,因此现在当用户更新文本框值时,该值不会在 bonus
属性 中的所有记录中自动更新 $scope.job.referrals
记录。
代码:
$scope.job.defaultBonus = 65;
function addNewReferrals{
$scope.job.referrals.push({
id: null,
bonus: $scope.job.defaultBonus
});
}
谁能告诉我为什么会这样,当 $scope.job.defaultBonus
发生变化时,我该如何更新 $scope.job.referrals
中的所有 bonus
属性?
正在侦听输入字段的更改。您需要 ng-model
和 ng-change
。 ng-model
将输入值绑定到范围对象。
<input ng-model='job.defaultBonus' ng-change='addNewReferrals()' />
您可以使用 map()
迭代数组并使用 {...}
展开运算符来更新记录。
function addNewReferrals() {
$scope.job.referrals = $scope.job.referrals.map(el => ({ ...el,
bonus: $scope.job.defaultBonus
}))
}
我为这个片段设置了一个名为 $scope
的对象来演示,但您只需使用 angular 属性 $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);