angularjs - Setting $scope.$watch on each element in an array -


i trying figure out how set $scope.$watch on each element in array. care attributes of each element.

in example, each rental_date object has 3 attributes: date, start_time, , stop_time. whenever start_time changed, want stop_time set 2 hours after start_time.

the $ngresource call (using angular 1.1.5):

agreement.show(    id: 5  ).$then ((success) ->   $scope.agreement = success.data.agreement    # returns array of rental dates   $scope.rental_dates = success.data.rental_dates    # $watch goes here 

here 4 variations of $watch function 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) ->     # tried '$scope.rental_dates[pos].start_time'      $log.info 'watch changed'     $log.info newval     $log.info oldval   ), true 

4:

this work, but, @ moment, can't think of elegant solution access values care $watching instead of whole array.

$scope.$watch 'rental_dates', ((newval, oldval) ->   $log.info 'watch changed'   $log.info newval   $log.info oldval ), true 

has done similar in own projects?

i assuming you're somehow using ng-repeat generate ui elements each entry of array? assign ng-controller each of these ui elements. controller instantiated each array element. inside controller, use $watch.

<div ng-repeat="rentaldate in rental_dates" ng-controller="rentaldatecontroller"> </div> 

and in controller code:

angular.module(...).controller('rentaldatecontroller', function ($scope) {     $scope.$watch('rentaldate.start_time', function (starttime) {         ...     }); }); 

here little example: http://plnkr.co/edit/lhj3mbulmahzdehcxvem?p=preview


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -