Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date object in Angular

Tags:

angularjs

Can someone explain why the input with ng-model in this plunk is not updated when the button is pressed?

http://plnkr.co/edit/8JpyUVM8dY8aoV4fi5hC?p=preview

HTML

  <body ng-controller="MainCtrl">
    Using ng-model:  <input type="text" ng-model="myDate"><br/>
    Using expression: {{ myDate  }}<br/>
    <button ng-click="nextDay()">Next Day</button>
  </body> 

JS

app.controller('MainCtrl', function($scope) {
  $scope.myDate = new Date();
  $scope.nextDay = function(){
    $scope.myDate.setDate($scope.myDate.getDate() + 1);
  };
});
like image 818
Warpasaur Avatar asked May 27 '15 18:05

Warpasaur


People also ask

What is a Date object?

The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.

What is the date format in angular?

AngularJS date Filter By default, the format is "MMM d, y" (Jan 5, 2016).

How do you create a Date object?

You can create a Date object using the Date() constructor of java. util. Date constructor as shown in the following example. The object created using this constructor represents the current time.


1 Answers

Working Plunker: http://plnkr.co/edit/ku8iy0YKvQfBdolg7cug?p=preview

Change your controller to:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.myDate = new Date();
  $scope.nextDay = function(){
     var newDate = new Date($scope.myDate.setDate($scope.myDate.getDate() + 1));
     $scope.myDate = newDate;
  };
});

Like others mentioned, the reference to the instance hasn't changed so Angular doesn't know it needs to render it again. By changing the Date object entirely you are forcing Angular to render the changed model.

like image 82
Carlos Perea Avatar answered Oct 13 '22 07:10

Carlos Perea