AngularJS - how to handle a circular clock?

Suppose I work with a directive that dates a date as a unix timestamp using two-way binding, but also offers a calendar widget to change the selection.

The calendar widget works with a date object, and I cannot change the format of the input data, and I do not want to rework the calendar to support the unix timestamp. This is also just an example, and this is a general way of working with circular observers.

The area will look like this:

scope.selectedUnixTimestamp; // this comes from the outside
scope.selectedDate;

scope.$watch('selectedUnixTimestamp', function(newV, oldV) {
    $scope.selectedDate = new Date(newV*1000);
});
scope.$watch('selectedDate', function(newV, oldV) {
    $scope.selectedUnixTimestamp = Math.floor(newV.getTime()/1000 + 0.000001);
});

My question is: what should I do to avoid extra calls $ watch callbacks? Obviously, if I select a new date, the stream will look like this:

  • Watcher # 2 is called - it changes the selected UnixTimestamp
  • Called by Watcher # 1 - it modifies selectedDate
  • Watcher # 2 ( ) - UnixTimestamp

, . ?


, - :

scope.selectedUnixTimestamp; 
scope.selectedDate;

var surpressWatch1 = false;
var surpressWatch2 = false;

scope.$watch('selectedUnixTimestamp', function(newV, oldV) {
    if(surpressWatch1) { surpressWatch1 = false; return; }
    $scope.selectedDate = new Date(newV*1000);
    surpressWatch2 = true;
});
scope.$watch('selectedDate', function(newV, oldV) {
    if(surpressWatch2) { surpressWatch2 = false; return; }
    $scope.selectedUnixTimestamp = Math.floor(newV.getTime()/1000 + 0.000001);
    surpressWatch1 = true;
});

.


- :

scope.selectedUnixTimestamp; 
scope.selectedDate;

scope.$watch('selectedUnixTimestamp', function(newV, oldV) {
    if(newV*1000 === scope.selectedDate.getTime()) { return; }
    $scope.selectedDate = new Date(newV*1000);
});
scope.$watch('selectedDate', function(newV, oldV) {
    if(scope.selectedUnixTimestamp*1000 === newV.getTime()) { return; }
    $scope.selectedUnixTimestamp = Math.floor(newV.getTime()/1000 + 0.000001);
});

, , * 1000


:

scope.$watch('selectedDate.getTime()', function(newV, oldV) {

+3
2

Angular : -, REST, , .

, . , , , ngModelController .

+1

? , , .

, , .

:

. , , , ( , ). , $watch :

$scope.$watch(function() {
    return {
        timestamp: scope.selectedUnixTimestamp, 
        date: scope.selectedDate
    }
}, function(newVal, oldVal) { 
    // Note that newVal and oldVal here is on the form of the object you return in the watch function, and hence have properties: timestamp and date.
    // You can compare newVal.date to oldVal.date (same with timestamp) to see which one has actually changed if you need to do that.
}
true);  // You need a deep watch (the true param) to watch the properties on the object
+2

All Articles