gpt4 book ai didi

javascript - AngularJS 观察对象数组中的对象属性

转载 作者:IT王子 更新时间:2023-10-29 03:00:30 26 4
gpt4 key购买 nike

我的 Controller 中有这个数据

    $scope.data = {
home: {
baseValue: "1",
name: "home"
},
contact: {
baseValue: "2",
name: "contract"
}
// a lot more options
};

像这样的一些 html:

<section class="content row" ng-repeat="item in data">
{{item.name}}
....
</section>

现在,我想知道 baseValue 何时更改,但由于我在数据变量中使用了一个对象,所以我无法以更简单的方式观察 属性。

我试过类似的方法,但我必须循环所有数组

$scope.$watch('data', function (newValue, oldValue, scope) {
// some code to compare the tow arrays, line by line
}, true);

我怎样才能做一个更简单的 $watch 来仅知道何时更改 baseValue

类似问题:

更新 1

我可以为每个对象添加一个单独的监视,以了解 baseValue 何时更改,但如果我有一个 n 个对象,那就不好了,不仅仅是这个例子中的几个对象

$scope.$watch('data.home', function (newValue, oldValue, scope) {
// do some stuff with newvalue.baseValue
}, true);

$scope.$watch('data.contact', function (newValue, oldValue, scope) {
// do some stuff with newvalue.baseValue
}, true);
... // Adds more individual `watch`

最佳答案

根据您的问题,您可以使用 ngChange 来观察 baseValue 的变化并触发函数。

HTML

<section class="content row" ng-repeat="item in data">
Name: {{item.name}} <br/>
BaseValue: <input type="text" ng-model="item.baseValue" ng-change="baseValueChange(item.baseValue)"/>
</section>

Controller

$scope.baseValueChange = function(baseValue) {
console.log("base value change", baseValue);
}

如果你是一个可以获取oldValue和newValue的更复杂的版本,你可以引用这个plunkr - http://plnkr.co/edit/hqWRG13gzT9H5hxmOIkO?p=preview

HTML

<section class="content row" ng-repeat="item in data">
Name: {{item.name}} <br/>
BaseValue: <input type="text" ng-init="item.oldBaseValue = item.baseValue" ng-model="item.baseValue" ng-change="baseValueChange(item.oldBaseValue, item.baseValue); item.oldBaseValue = item.baseValue"/>
</section>

Controller

$scope.baseValueChange = function(oldVal, newVal) {
console.log("base value change", oldVal, newVal);
}

关于javascript - AngularJS 观察对象数组中的对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24876944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com