0

I'm wondering, why passing a simple variable as the parameter to the filter is not working:

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>

Why the last one is not formatted?

Thanks

1
  • Have you tried passing $scope.format2 instead? Commented Jun 13, 2016 at 11:06

5 Answers 5

2

Test is not defined on the scope and therefore not available in the binding.

You can read a little about scope vs. global variables here: http://jacopretorius.net/2015/04/working-with-global-variables-in-angularjs.html

The key here is how Angular interprets the expressions between the curly braces. You might expect Angular to do a simple eval on the code, but that is not the case - Angular actually uses JavaScript to parse these JavaScript-like syntax within the context of the current scope.

Sign up to request clarification or add additional context in comments.

Comments

1

because you didn't expose Test to the scope.

$scope.Test = Test;

would do the trick.

Comments

1

If you want to access a controller variable in html , it should be in $scope. The test you were accessing is a local variable.

Comments

1

Test is not defined in your scope. You have to bind Test into $scope.

Comments

1

Define Test in scope:

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;
}

See working http://jsfiddle.net/da2w2jdL/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.