Utilizing a variable in an Angular filter

Curious about why passing a simple variable as the parameter to the filter is not working:

Javascript:

let 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>

Any reason why the last one isn't properly formatted?

Appreciate any insights!

Answer №1

Error occurs when 'Test' is not defined within the scope and therefore cannot be accessed in the binding.

To gain a better understanding of scope versus global variables, you can find more information here:

Angular interprets expressions within curly braces using JavaScript rather than simply evaluating the code. It parses this JavaScript-like syntax within the current scope context.

Answer №2

The reason it didn't work is because Test wasn't made accessible in the scope.

$scope.Test = Test;

Adding this line of code should solve the issue.

Answer №3

In order to retrieve a controller variable within an HTML page, it needs to be defined within the $scope. The specific variable that you attempted to access is actually a local variable.

Answer №4

There seems to be an issue with the Test variable in your current scope. You need to properly bind Test within $scope for it to be accessible.

Answer №5

Explain the Test function 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;
}

To view a live example, visit: http://jsfiddle.net/da2w2jdL/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to make a jQuery Ajax HTTP Request within a Chrome extension

I'm facing an issue with sending a jQuery Ajax HTTP Request within google chrome extensions. I have already imported the jQuery library and used the following code: $.ajax({ method: "PUT", url: "https://spreadsheets.google ...

In the scenario where there are duplicate 'id' keys within the array of objects, what is the best method to remove the object with the duplicate key?

When there are duplicate 'id' keys among the objects in the array, how can you remove the object with the duplicated 'id'? I attempted to use filter, map, and set methods, but none of them were successful. Since the array is not one-di ...

Fetching Data from DataTable using AJAX in Codeigniter

I am currently developing an application using CodeIgniter. Below is the code: Controller: public function index(){ $data = array( 'record' => $this->Parameter_model->get_parameter('tbl_parameter') ); ...

Dealing with errors in Express.js within the service or controller layers

Currently, I am developing an Express.js application with a distinct controller layer and service layer. Below you can find the code snippet I have implemented so far: user.service.js exports.registerUser = async function (email, password) { const hash ...

Learn how to implement a call to 'next()' in Express and Node.js only after successfully creating schemas

I am currently developing an event app, and within my 'Event' schema, I have an array of 'Tag' schemas, allowing each event to be associated with one or more tags. Event: var EventSchema = new Schema({ ... tags: [{ type: Schema.Type ...

What is the process for reversing styles on the second click?

This is the script I've written: function displayPanel(index, colorCode) { buttons.forEach(function(button){ button.style.borderBottom=""; }); tabButtons[index].style.borderBottom="none"; panels.forEach(function(panel){ ...

Rendering external HTML content within a React component can be achieved by utilizing parsing techniques

In my React application, I have a component that receives HTML content as a string field in the props from an API call. My objectives are: To render this HTML content with styles applied. To parse the content and detect "accept-comments" tags within sec ...

Utilize JQuery's appendTo() method along with html() function for seamless content replacement

I have a question about appending and replacing div elements. I am currently using the following code: $('.toggle_questions').appendTo('#'+sectionId).show(); While this works perfectly to append my div with the class .toggle_questions ...

Properly segmenting sections into components in Angular

My project has a specific folder structure as shown below: https://i.sstatic.net/7oihC.png In my list-page, I perform operations such as create, update, and delete using modal dialogs. I am considering creating 4 pages for each of these CRUD operations a ...

How to access a specific element within an ng-grid

My grid options include: $scope.ngOptions = { data: 'data', columnDefs: [ {field: 'Status', displayName: "Status", cellTemplate: selectTableTemplate, enableCellEdit: true}, {cellTemplate: &apos ...

Can you explain the function of the "staticMoving" property in TrackballControls?

I was exploring the library module known as THREE.TrackballControls when I came across an interesting property within an instance of the module called staticMoving. This property appears to be connected to another property called dynamicDampingFactor. Howe ...

Issues with error handling in ExpressJS arise frequently

In the server.js file, towards the very end, there is a block of code that appears to handle errors: app.use(logErrors); function logErrors (err: Error, req: Request, res: Response, next: NextFunction) { console.log(err); mongoDal ...

Verify and generate a notification if the value is null

Before saving, it is important to check for any null values and alert them. I have attempted to do so with the following code, but instead of alerting the null values, the data is being saved. . function fn_publish() { var SessionNames = getParamet ...

Utilizing the onscroll feature to trigger a function within a ScrollView

I am facing an issue with an animated view where I need to execute multiple events within the onScroll property. The current onScroll implementation is as follows: onScroll={ Animated.event( [{ nativeEvent: { conten ...

Could you guide me on how to utilize Sencha Touch for saving information in a JSON file?

I am in the process of creating a simple Sencha Touch application to become more comfortable with the platform. My goal is to have the store (currently set up as shown below) read and write data to/from a local JSON file. Additionally, I would like the sto ...

The type 'Navigator' does not have the property 'userAgentData' in its definition

Since I'm looking to minimize the information provided by navigator.userAgent, I decided to migrate to User-Agent Client Hints. However, I've encountered an error while attempting to do so: https://i.stack.imgur.com/lgIl7.png Could someone plea ...

Looking to create a format for displaying short comic strips in a grid pattern

I am struggling to create an image grid for my small comics. I want to have 2 columns and 3 rows, but all the divs end up in the same place. I tried using display: flex, but it didn't work as expected. Additionally, I want the grid to be responsive, b ...

Having difficulty updating a web page while utilizing setInterval() and passing a function that utilizes document.write to display JavaScript content on the page

At the core of my issue lies a blank HTML page that incorporates a JavaScript file, with the following code in the JavaScript file: function doIt() { document.writeln("asdf"); } // Alternatively, you can use setTimeout setInterval("doIt()", 5000); Upon ...

Pressing an HTML button can enable and disable the pause and resume functions

Currently, I am working on an audio player where I need to implement functionality to pause and resume the playback. I have already set up the pause() and resume() functions in my script. The issue I am facing is related to the HTML button that triggers th ...

Learn how to use Angular2 or TypeScript to display 'unsubscribe' and 'subscribe' text on a toggle button

I'm working on a toggle button that initially displays the word subscribe on the thumb. When the toggle is disabled, I want it to show unsubscribe instead. Can someone please help me achieve this functionality? Here's the code snippet: <md-s ...