我在一个控制器中使用了两个AngularJS Bootstrap-ui Datepicker指令。
代码很简单,视图:
<div class="row">
<div class="col-md-6">
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="dd-MM-yyyy" ng-model="startDate" is-open="startDateOpened" min="minDate" max="'2015-06-22'" ng-required="true" close-text="Close" />
<span class="input-group-btn">
<button class="btn btn-default" ng-click="open($event, 'startDateOpened')"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
</div>
<div class="col-md-6">
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="dd-MM-yyyy" ng-model="endDate" is-open="endDateOpened" min="minDate" max="'2015-06-22'" ng-required="true" close-text="Close" />
<span class="input-group-btn">
<button class="btn btn-default" ng-click="open($event, 'endDateOpened')"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
</div>
</div>
控制器(部分)。
var now = new Date();
var startDate = $scope.startDate = new Date(now.getFullYear(), now.getMonth(), 1); // beginning of month
var endDate = $scope.endDate = now;
$scope.$watchCollection('[startDate, endDate]', function (newVals, oldVals) {
if(!(newVals[0] === oldVals[0] && newVals[1] === oldVals[1])){
console.log('old values', oldVals);
console.log('new values', newVals);
print();
}
});
function print() {
console.log('startDate !', startDate);
console.log('endDate !', endDate);
}
$scope.open = function($event, name) {
$event.preventDefault();
$event.stopPropagation();
$scope[name] = true;
};
我正在分配两个模型 - startDate
和endDate
。一切看起来工作正常,当我在任一日期选择器$scope.$watchCollection()
中选择日期时,回调被触发,但oldVals
始终 eqaul到newVals
所以模型并没有真正改变(即使触发了更改事件监听器)。
我做错了什么?我猜这是缺乏基本的理解:)
由于
修改
@Maxim使用深度监视的答案确实解决了我不进入if
声明的问题。现在我的另一个问题是回调中的print
函数总是打印startDate
和endDate
的旧值
答案 0 :(得分:1)
尝试$watch
标志为true
又名深度观察:
$scope.$watch('[startDate, endDate]', function (newVals, oldVals) {
if(!(newVals[0] === oldVals[0] && newVals[1] === oldVals[1])){
console.log('old values', oldVals);
console.log('new values', newVals);
startDate = newVals[0];
endDate = newVals[1];
}
}, true);