数组中的每个元素设置$范围。$腕表 [英] Setting $scope.$watch on each element in an array
问题描述
我试图找出如何设置 $范围。$看
数组中的每个元素。我只在乎每个元素的某些属性。
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.
在我的例子中,每个 rental_date
对象有三个属性:日期
, START_TIME
和 STOP_TIME
。每当 START_TIME
被改变,我想在 STOP_TIME
后,设置为2小时 START_TIME
。
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
.
的 $ 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
下面是 $观看
函数我试过的四个变化:
Here are the four variations of the $watch
function I tried:
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
这不工作,但是,此刻,我想不出一个优雅的解决方案,以获取有关 $只有我在乎的价值观看
ING而不是整个数组。
4:
This does work, but, at the moment, I can't think of an elegant solution to access only the values I care about $watch
ing 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?
推荐答案
我假设你正在使用某种方式NG-重复生成数组中的每个条目的UI元素?分配NG-控制器,这些UI元素。控制器将被实例化的每个数组元素。该控制器内部,使用$手表。
I am assuming you're somehow using ng-repeat to generate UI elements for each entry of the array? Assign an ng-controller to each of these UI elements. The controller will be instantiated for each array element. Inside that controller, use $watch.
<div ng-repeat="rentalDate in rental_dates" ng-controller="RentalDateController">
</div>
然后在你的控制器code:
And then in your controller code:
angular.module(...).controller('RentalDateController', function ($scope) {
$scope.$watch('rentalDate.start_time', function (startTime) {
...
});
});
下面是一个小例子:<一href=\"http://plnkr.co/edit/lhJ3MbULmahzdehCxVeM?p=$p$pview\">http://plnkr.co/edit/lhJ3MbULmahzdehCxVeM?p=$p$pview
这篇关于数组中的每个元素设置$范围。$腕表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!