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);
};
});
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.
AngularJS date Filter By default, the format is "MMM d, y" (Jan 5, 2016).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With