gpt4 book ai didi

javascript - 如何在 $scope 中的两个变量之间设置双向绑定(bind)

转载 作者:行者123 更新时间:2023-11-28 01:10:14 25 4
gpt4 key购买 nike

我有currentDistrict以显示在页面上。初始化为空字符串:

$scope.currentDistrict = '';

以及稍后使用 WebAPI 调用填充:

...
$scope.currentDistrict = data.currentDistrict;
...

检索到的地区信息显示在指令中:

<district-selector current="currentDistrict"></district-selector>

此外,页面中有一个表单,使用 json 对象:

$scope.address = {
'district': $scope.currentDistrict,
'name': '',
'street': '',
'city': '',
'state': '',
'zip': '',
'comments': ''
};

表单正在使用此 address对象:

我希望 $scope.address.district值将随着currentDistrict一起改变。比如说,如果我改变当前的分区,不仅仅是<district-selector>将会改变,但是表单中的只读文本框也应该改变。

但它永远不会。

所以问题是:如何更改 $scope.address.district$scope.currentDistrict 发生变化时?

如果'district': $scope.currentDistrict,不会设置绑定(bind),监听一个变量的变化并应用于另一个变量的正确方法是什么?

最佳答案

这种情况非常适合 $watch 功能:

$scope.$watch('currentDistrict', function(newVal, oldVal) {
$scope.address.district = newVal;
});

通过在 Controller 中设置此监视,每当 currentDistrict 的值发生变化时,它都会反射(reflect)在 address.district 中。

关于javascript - 如何在 $scope 中的两个变量之间设置双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24534876/

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