Having trouble accessing the value from an isolated scope in an AngularJS directive

I have developed a unique directive to format datetime that works seamlessly in multiple views, except for one specific instance. Upon passing request.created to it (as seen in the HTML below), while console.logging(scope) displays "date" correctly set and passed to the directive, console.logging(scope.date) shows an empty result.

Everything functions properly in other views and with several "email.sendDate"s within the same view.

The value of request is fetched from the server and implemented by the controller.

myApp.directive('friendlydate', function () {
   function link(scope, element, attrs) {
       console.log(scope);
       console.log(scope.date);
       var uglydate = scope.date;
       //perform actions
        scope.formatteddate = prettydate;
    };

   return {
       restrict: 'E',
       scope: {
         date: '@'
       },
       link: link,
       template: '{{formatteddate}}'
   };
});

In my html, I have

<div class="col-md-6">
  <dl class="dl-horizontal">
    <dt>Created</dt>
    <dd>
      <friendlydate date="{{request.created}}"></friendlydate>
    </dd>
    <dt>IP Address</dt>
    <dd>{{request.ipAddress}}</dd>
    <dt>Browser</dt>
    <dd>{{request.browser}}</dd>
  </dl>
</div>

<table>
  <tbody ng-repeat="email in request.emails">
    <tr>
      <td>
        <friendlydate date="{{email.sendDate}}"></friendlydate>
      </td>
      <td>{{email.subject}}</td>
      <td>{{emailStatus(email.status)}}</td>
      <td><button class="btn btn-primary">view</button></td>
    </tr>
  </tbody>
</table>

If more information is needed, feel free to ask. I am close to losing my mind, please provide assistance.

Answer №1

Your data is fetched from the server and manipulated by the controller. There may be a slight delay in receiving a response, but my solution should work for you.

To implement this in your view, you can use ng-if:

<friendlydate date="{{request.created}}" data-ng-if="request.created"></friendlydate>

Alternatively, you can utilize scope.$watch in your directive:

myApp.directive('friendlydate', function () {
    function link(scope, element, attrs) {
        scope.$watch(function () {
            console.log(scope);
            console.log(scope.date);
            var uglydate = scope.date;
            // perform operations
            scope.formatteddate = prettydate;
        });
    };

    return {
        restrict: 'E',
        scope: {
            date: '@'
        },
        link: link,
        template: '{{formatteddate}}'
    };
});

Answer №2

Consider taking a different approach that will enhance the visual appeal and simplify maintenance.

Implement a filter

angular.module('myApp.filters', [])
.filter('friendlyDate', function($moment, $translate) {
  return function(value, format) {
    if(format){
      // You can pass parameters to customize the format
      // return formatWithFormat(value,format);
    }
    return friendlyFormat(value);
  };
});

Your template should look like this:

<div class="col-md-6">
  <dl class="dl-horizontal">
    <dt>Created</dt>
    <dd> {{request.created | friendlyDate: 'MM/YYYY'}} </dd>
    <dt>IP Address</dt>
    <dd>{{request.ipAddress}}</dd>
    <dt>Browser</dt>
    <dd>{{request.browser}}</dd>
  </dl>
</div>

<table>
  <tbody ng-repeat="email in request.emails">
    <tr>
      <td>{{email.sendDate | friendlyDate}} </td>
      <td>{{email.subject}}</td>
      <td>{{emailStatus(email.status)}}</td>
      <td><button class="btn btn-primary">view</button></td>
    </tr>
  </tbody>
</table>

I also recommend using angular-moment for various date formats.

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

What is the correct way to utilize the JSON.parse() function in javascript?

Recently, I've been working with an array printed in JSON format. [{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}] Unexpectedly, I had to split the JSON array into two parts for some reason. When de ...

The trouble with NodeJS Socket.IO: why indexOf won't cooperate

I can't figure out why my indexOf function isn't working! Each time a user loads a page on the website, the server receives the "data" variable containing the user's name. client.js : $.ajax({ type: "POST", url: "ajax.php", data ...

The functionality of uploading files in Dropzone.js is not supported on Windows operating systems

I am currently working on a file uploader using dropzone functionality. I will share the code with you shortly, but first let me outline the problem: My setup consists of an Ubuntu machine running the server code in node.js using the multer library. The f ...

I would like to create a border for the radial gradient and apply it to the div as well

Below is the CSS code I have written. div { height: 150px; margin: 5em 2em; background: radial-gradient(circle at top center, transparent, transparent 70px, black 70px, black); border-radius: 8p## Heading ##x; position: relative; } .circle { ...

What is the best way to populate a select input field with options using JavaScript?

When I am loading an HTML table, there is a select input field that needs to display some options. Immediately after constructing the HTML table row, I invoke a function to populate this input field using its class. Below is the relevant HTML snippet and ...

Separate the React code from the application's codebase

Transitioning from jQuery to React, I am seeking guidance on configuring webpack to separate my code from the core React functionality. I am developing widgets with React, where each widget functions as its own "app" and can be integrated into non-React ...

Toggling dropdown menus with conditional Jquery statements

I am experiencing some discomfort. :) I've been working on a calorie calculator that includes a dropdown for various dietary preferences. Currently, when a user clicks the button, the dropdown appears and disappears when clicking outside the button. ...

Access nested objects in Javascript (Vue)

Struggling with a simple question as a beginner... I am dealing with an object of objects: monsters { place1: { monster1: { ... } monster2: { ... } } place2: { monster3: { ... } monster4: { ... } } } I ...

Importing a JavaScript file into another JavaScript file as text in React Native can be a convenient way

In my project, I have a file named MyFirstPage.js that contains the following code snippet: renderCards() { let icon = this.state.icon; .... .... .... } This code is responsible for rendering cards within the main render function. However, as the ...

The property 'hasClass' cannot be retrieved from an undefined or null reference

I'm currently utilizing the AngularJS framework and implementing 'hasClass' within jQuery to create a dropdown on mouse over. The functionality works smoothly in Chrome and Firefox, but I encounter an error in IE stating "Unable to get Prope ...

Jquery code that mimics pressing a key downwards is not functioning properly to execute a keyboard shortcut

I would like to express my gratitude in advance for any time and effort dedicated to this matter. So, here's the situation: I have a script that is meant to simulate a key press event after 3 seconds once the page is loaded. The goal was to trigger a ...

Transforming jQuery into vanilla JavaScript in order to create a customized dropdown select functionality

I am struggling with converting jQuery code to pure JavaScript for a custom select element. https://codepen.io/PeterGeller/pen/wksIF After referencing the CodePen example, I attempted to implement it with 3 select elements. const select = document.get ...

Loop through the tabs array and display varying views based on conditionals

I am currently working on building tabs and tab panels iteratively to display information, but I am facing issues in getting the desired output. For each name in a list, I need to create a tab and a corresponding tab panel underneath it. For example, the ...

Enhance jQuery for a dynamic navigation dropdown with multiple sub-menus

Looking for help with a jQuery script as I am a beginner in using jQuery. jQuery(document).ready(function ($) { $(".sub-menu").hide(); $(".current_page_item .sub-menu").slideDown(200);; $("li.menu-item").click(function () { if ($('.sub-menu&apos ...

AngularJS inputs using ng-model should be blank when in the pristine state

Check out this input element within an HTML form: <input ng-model="amount" /> Currently, the input displays as $scope.amount = 0 in the controller. I want to start with a blank input field instead. This way, users can easily input data without havi ...

Troubleshooting Async Issue with Promises in JS/Vue

Greetings and thank you for taking the time to read my query. Within my Vue component, named 'interactiveChart', there is a specific sequence of actions that occur when mounted: I begin by initializing various components such as the db manage ...

The range input in HTML does not respond when attempting to adjust it

I am having an issue where the thumb on the slider does not move when I try to. This problem occurred after I inserted an img element inside the slider-cntnr div. View the code at http://codepen.io/danielyaa5/pen/xVEXvB HTML <div id="slider-cntnr"&g ...

combine object with an array attribute

If we have the following objects: let firstObject = {items: ["apple"]}; let secondObject = {items: ["orange"]}; and then execute Object.assign(firstObject, secondObject); the new state will be: firstObject.items[0] //"orange" firstObject.items === sec ...

Confusion between modules and classes in Node.js when using CoffeeScript

I'm struggling to understand how to use Protoype in CoffeeScript, even though I am familiar with using it in standard Javascript with Node.js and modules. Imagine I have a file named mymodule.coffee: Module = {} class MyModule constructor: (para ...

Having issues with getting Bootstrap to function properly in my create-react-app

I've been attempting to use traditional Bootstrap instead of react-bootstrap to render my React component, but I can't seem to get it right. I've installed Bootstrap via npm and included the CDN links and scripts as well. Despite trying vari ...