我想弄清楚如何设置$scope.$watch
在数组中的每个元素上。我只关心每个元素的某些属性。
在我的例子中,每个rental_date
对象具有三个属性:date
, start_time
, and stop_time
。每当start_time
已更改,我想要stop_time
设置为2小时后start_time
.
The $ngResource
调用(使用角度 1.1.5):
Agreement.show(
id: 5
).$then ((success) ->
$scope.agreement = success.data.agreement
# returns an array of rental dates
$scope.rental_dates = success.data.rental_dates
# $watch goes here
以下是四种变体$watch
我尝试过的功能:
1:
angular.forEach $scope.rental_dates, (date, pos) ->
$scope.$watch date.start_time, ((newval, oldval) ->
$log.info 'watch changed'
$log.info newval
$log.info oldval
), true
2:
angular.forEach $scope.rental_dates, (date, pos) ->
$scope.$watch $scope.rental_dates[pos].start_time, ((newval, oldval) ->
$log.info 'watch changed'
$log.info newval
$log.info oldval
), true
3:
angular.forEach $scope.rental_dates, (date, pos) ->
$scope.$watch 'rental_dates[pos].start_time', ((newval, oldval) ->
# also tried '$scope.rental_dates[pos].start_time'
$log.info 'watch changed'
$log.info newval
$log.info oldval
), true
4:
这确实有效,但是目前,我想不出一个优雅的解决方案来仅访问我关心的值$watch
ing 而不是整个数组。
$scope.$watch 'rental_dates', ((newval, oldval) ->
$log.info 'watch changed'
$log.info newval
$log.info oldval
), true
有人在自己的项目中做过类似的事情吗?