In a fairly complicated angular web app, I need the dynamic year to show up in a footer that doesn't have a directive. Is there an angular way to do it using just {{SomeDateFunction()}}
?
I've seen people say {{Date.now() | date:'yyyy'}}
, which doesn't display anything. I've tried {{new Date().getFullYear()}}
which breaks angular and the error says
Syntax Error: Token 'Date' is an unexpected token at column 5 of the expression [new Date().getFullYear()] starting at [Date().getFullYear(].
I don't want to link a scope from the root scope, or put this in a directive just for the year, this is exactly the kind of thing {{ }} expressions should be able to solve, and non-date related simple {{ }} expressions display just fine.
Using new Date() constructor The new Date() constructor contains a getFullYear() method, which returns the current year in four-digit (2020) format according to the user local time. Here is an example, that renders the current year in the footer component of our angular app.
To get the current year in TypeScript: Call the new Date() constructor to get a date object for the current date. Call the getFullYear() method on the date object. The getFullYear method will return a number that represents the current year.
To get the current year, you can call the getFullYear() method will return the year of the specified Date according to local time. The value returned by is an absolute number. For the dates between 1000 and 9999 years, the getFullYear() method returns a four-digit number.
To get the current year in JavaScript, call the new Date() constructor to get a date object and call the getFullYear() method on the result, e.g. new Date(). getFullYear() . The getFullYear method will return a number corresponding to the current year.
You need to define the date object inside the controller onto the scope.
$scope.date = new Date();
And then in view do
{{date| date:'yyyy'}}
Its pretty late to response and hopefully you have already got the answer. Giving the answer for everybody's sake, -
(function(angular) {
'use strict';
var app = angular.module("myApp", []);
app.controller('dateController', function($scope) {
$scope.SomeDateFunction = function() {
var currentdate = new Date();
return currentdate.getFullYear();
}
});
})(window.angular);
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="1.6.4" src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="dateController">
<h1>Hello World!</h1> © this is copyright protected as of {{SomeDateFunction()}}
</div>
</body>
</html>
it should get you what you want.
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