I am trying to figure out how to set a $scope.$watch on each element in an array. I only care about certain attributes of each element.
In my example, each rental_date object has three attributes: date, start_time, and stop_time. Whenever the start_time is changed, I want the stop_time to be set to 2 hours after the start_time.
The $ngResource call (using Angular 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
Here are the four variations of the $watch function I tried:
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:
This does work, but, at the moment, I can't think of an elegant solution to access only the values I care about $watching instead of the whole array.
$scope.$watch 'rental_dates', ((newval, oldval) ->
$log.info 'watch changed'
$log.info newval
$log.info oldval
), true
Has anybody done something similar in their own projects?
start_timechange in your code ? Is it a user action or at least something you can track ? For something like this, if possible, I'd try to watch an array made with the ids of the values changed, then you watch this array instead of the whole data (but it needs to change the part of your code that modifies thestart_time)start_timeandstop_timeare bound to Angular UI'stimepickerdirective. Whenever the user changes thestart_time, I want thestop_timeto be set to two hours afterwards.