2016-06-13 200 views
0

我想知道,爲什麼通過一個簡單的變量作爲參數傳遞給過濾器不工作:傳遞一個變量角度濾波

的Javascript:

var Test = Test || {}; 
Test.Constants = {}; 
Test.Constants.DateFormat = 'dd/MM/yyyy hh:mm'; 

function Main($scope){ 
    $scope.date = new Date(); 
    $scope.format = 'dd/MM/yyyy hh:mm'; 
    $scope.format2 = Test.Constants.DateFormat; 
}  

HTML:

<div> 
    {{date}}<br> // "2016-06-13T10:29:49.935Z" 
    {{date | date: 'dd/MM/yyyy hh:mm'}}<br> // 13/06/2016 02:29 
    {{date | date: format}}<br> // 13/06/2016 02:29 
    {{date | date: format2}}<br> // 13/06/2016 02:29 
    {{date | date: Test.Constants.DateFormat}} // Jun 13, 2016 
</div> 

爲什麼最後一個沒有格式化?

由於

+0

你試過路過'$ scope.format2'呢? – AranS

回答

2

Test未在範圍限定,並且因此在結合不可用。

你可以閱讀一些關於範圍與這裏的全局變量:http://jacopretorius.net/2015/04/working-with-global-variables-in-angularjs.html

這裏的關鍵是如何角解釋 花括號之間的表達式。您可能希望Angular對 代碼進行簡單的評估,但情況並非如此 - Angular實際上使用JavaScript來解析當前的 範圍內的JavaScript類語法。

1

因爲您沒有向範圍披露Test

$scope.Test = Test; 

會做的伎倆。

1

如果你想在html中訪問控制器變量,它應該在$ scope中。您正在訪問的測試是一個局部變量。

1

測試未在您的範圍內定義。您必須將Test綁定到$ scope。

1

定義Test範圍:

function Main($scope) { 

    $scope.Test = $scope.Test || {}; 
    $scope.Test.Constants = {}; 
    $scope.Test.Constants.DateFormat = 'MMM d, y'; 

    $scope.date = new Date(); 
    $scope.format = 'dd/MM/yyyy hh:mm'; 
    $scope.format2 = $scope.Test.Constants.DateFormat; 
} 

見工作http://jsfiddle.net/da2w2jdL/