作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有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/
我是一名优秀的程序员,十分优秀!