简体   繁体   English

AngularJS:$ scope。$ watch两个互相依赖的值

[英]AngularJS: $scope.$watch two values that depend on each other

I have an AngularJS app with a date range where the end date always has to be 11 months after the start date (for a total duration of 12 months). 我有一个AngularJS应用,其日期范围的结束日期总是必须比开始日期晚11个月(总持续时间为12个月)。 The user needs to be able to go into the view and edit either the start or end date. 用户需要能够进入视图并编辑开始或结束日期。 So if they edit the start date, the end date adjusts to 11 months after the start date. 因此,如果他们编辑开始日期,则结束日期将调整为开始日期之后的11个月。 And if they edit the end date, the start date adjusts to 11 months before the end date. 如果他们编辑结束日期,则开始日期会调整为结束日期之前的11个月。

The problem is that when either of these dates change, they trigger an AJAX call to the server, but the way it's working now, they are triggering two calls because when one date changes, so does the other. 问题在于,当这两个日期中的任何一个发生更改时,它们都会触发对服务器的AJAX调用,但是现在它的工作方式是,它们会触发两个调用,因为当一个日期更改时,另一个日期也会更改。

I'm trying use $scope.$watch('startDate') and $scope.$watch('endDate') to detect changes in my controller, but am struggling to find a way to change both values at once, but only trigger one AJAX server call. 我正在尝试使用$scope.$watch('startDate')$scope.$watch('endDate')来检测控制器中的更改,但是正在努力寻找一种方法来一次更改两个值,但只能触发一个AJAX服务器调用。

Any ideas on how to keep both dates in line, but avoid duplicate AJAX calls and $scope.$watch() loops? 关于如何使两个日期保持一致的任何想法,但避免重复的AJAX调用和$scope.$watch()循环?

Thanks to BenFelda's suggestion, I was able to piece together some code that did what I wanted using g00fy's datepicker and ng-change . 感谢BenFelda的建议,我得以使用g00fy的datepicker和ng-change将一些代码组合在一起,实现了我想要的功能。

view: 视图:

<div ng-model="startDate" ng-change="startDateChanged()" date-picker="startDate" min-view="month"></div>

controller: 控制器:

$scope.startDateChanged = function() {
    console.log('the start date changed!');
    console.log($scope.startDate);
    //make AJAX call, which only happens once
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM