gpt4 book ai didi

angularjs - 在数组中的每个元素上设置 $scope.$watch

转载 作者:行者123 更新时间:2023-12-03 22:50:00 26 4
gpt4 key购买 nike

我想弄清楚如何设置 $scope.$watch在数组中的每个元素上。我只关心每个元素的某些属性。

在我的例子中,每个 rental_date对象具有三个属性:date , start_time , 和 stop_time .每当start_time改了,我要stop_time设置为 start_time 后 2 小时.
$ngResource调用(使用 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

以下是 $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

有没有人在自己的项目中做过类似的事情?

最佳答案

我假设您以某种方式使用 ng-repeat 为数组的每个条目生成 UI 元素?为每个 UI 元素分配一个 ng-controller。将为每个数组元素实例化 Controller 。在该 Controller 中,使用 $watch。

<div ng-repeat="rentalDate in rental_dates" ng-controller="RentalDateController">
</div>

然后在您的 Controller 代码中:
angular.module(...).controller('RentalDateController', function ($scope) {
$scope.$watch('rentalDate.start_time', function (startTime) {
...
});
});

这是一个小例子: http://plnkr.co/edit/lhJ3MbULmahzdehCxVeM?p=preview

关于angularjs - 在数组中的每个元素上设置 $scope.$watch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18106649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com