当它被放置在数组中的元素上时,我无法观察它的作品;
请参阅示例:http://jsfiddle.net/zwrza551/2/
<div ng-app>
<div ng-controller="Test">
Name: <input type="text" ng-model="customer.name" />
<hr/>
<div ng-repeat="address in customer.addresses">
<input type="text" ng-model="address.name" />
<input type="text" ng-model="address.zipcode" />
<hr />
</div>
</div>
</div>
function Test($scope){
$scope.customer = {
name: 'Customer 1',
addresses: [
{ name: 'Address 1', zipcode: 123456, city: null, state: null },
{ name: 'Address 2', zipcode: 234567, city: null, state: null },
{ name: 'Address 3', zipcode: 456787, city: null, state: null },
{ name: 'Address 4', zipcode: 675684, city: null, state: null }
]
};
$scope.$watch('customer.name', function(newName, oldName){
console.log(newName);
});
$scope.$watch('address.zipcode', function(newCode, oldCode){
console.log(newCode);
//Make request to webservice, get addres for zipcode set city and state from this address.
});
}
在我可以的客户名称上,因为地址数组不起作用。
答案 0 :(得分:0)
尝试一下:
$scope.$watch('customer.addresses', function(newCode, oldCode){
for (... every address in customer.addresses) {
// check if city and state are null and do the request if it is true
}
}, true);
别忘了打开深表开关。 (第3个参数true
)
该开关可以检查女巫angular.equals
,而不是比较参考,这会导致你的阵列被观察其元素的变化。
答案 1 :(得分:0)
Ng-repeat有自己的范围,所以你不能写'address.zipcode&#39;外。 (我的意思是,你可以写,但这将解决另一个变量) 你可以写:
$scope.$watch('customer.addresses[0].zipcode', function(newCode, oldCode){
console.log(newCode);
});
对所有指数都一样......但正如之前所说,更好地使用ng-change。 http://jsfiddle.net/qnb5aL1p/
答案 2 :(得分:0)
你可以使用这个工作.i:e添加多个手表,但更好地使用ng-change @Petr已经在上面解释了
您正面临这个问题,因为ng-repeat有自己独立的范围,这超出了您当前的范围范围。
for (var i = 0; i < $scope.customer.addresses.length; i++) {
$scope.$watch('customer.addresses[' + i + ']',function(newValue, oldValue) {
console.log(newValue.zipcode + ":::" + oldValue.zipcode);
}, true);
}