2017-01-05 32 views
9

在一個相當複雜的角度web應用程序中,我需要動態的一年顯示在沒有指令的頁腳中。有沒有一種角度的方式來使用它只使用{{SomeDateFunction()}}如何僅通過{{}}獲取Angular 1中的當前年份?

我見過有人說{{Date.now() | date:'yyyy'}},它沒有顯示任何東西。我已經試過{{new Date().getFullYear()}}打破角度和錯誤說

Syntax Error: Token 'Date' is an unexpected token at column 5 of the expression [new Date().getFullYear()] starting at [Date().getFullYear(].

我不想一個範圍從根範圍的指令,只爲一年鏈接,或者把這個,這正是{{}}表達式應該能夠解決的事情,而非日期相關的簡單{{}}表達式顯示得很好。

+2

我想你誤解了角度表達式。他們不執行任意JavaScript,而是綁定到'$ scope'上的屬性。如果你碰巧有一個屬於'$ scope'的屬性,它是一個函數,它們將執行該函數。 – Claies

+2

https://docs.angularjs.org/guide/expression 'Date'是'window'對象的成員。 Angular表達式不使用'eval',因此不要將'window'對象暴露給表達式。您需要查看下面的'squiroid's'答案以獲得合法的解決方案。 –

+0

我想我是表達式與功能混淆,感謝您的洞察力。 – Bronanaza

回答

13

您需要將控制器內的日期對象定義到範圍內。

$scope.date = new Date(); 

然後在視圖做

{{date| date:'yyyy'}} 
+1

這不是我想聽到的,但感謝您的確認。 – Bronanaza

2

它相當晚的反應,希望你已經得到了答案。給每個人的緣故答案, -

(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> &copy; this is copyright protected as of {{SomeDateFunction()}} 
 
    </div> 
 
</body> 
 

 
</html>

它應該得到你想要的東西。

相關問題