Lack of information occurs when sending an object to a directive within AngularJS

How can an object be passed to a directive in order to access the users data within the directive's scope? Despite attempts, I have been unsuccessful. Here is what I've done:

Within my controller, I assigned an array of users to a scope:

$scope.users = payload.data.results;

Next, I attempted to pass this object to my directive as an attribute:

<display test123='users'></display>

The directive's function:

function ListDisplay() {
    var directive = {
      replace: 'true',
      restrict: 'E',
      scope: {
        test123: '='
      },
      controller: ListDisplayController,
      controllerAs: 'vm',
      bindToController: true,
      link: ListDisplayLinkFunc
    };

    return directive;


    function ListDisplayController($scope) {
      console.log($scope.test123);

    }

    function ListDisplayLinkFunc(scope, elem, attr) {

      console.log(scope.test123);
    }
  }

However, when attempting to display scope.data, it returns undefined.

Answer №1

When utilizing controllerAs: 'vm' and bindToController: true, any values passed in the scope are assigned to a variable named vm.

Consider implementing the following:

function ListDisplayController($scope) {
  var vm = this;
  console.log(vm.test123);
}

To handle usage of "bindToController" in the link function, you can use:

function ListDisplayLinkFunc(scope, elem, attr) {
  console.log(scope.vm.test123);
}

You can view an example of this in action on this plunker: http://plnkr.co/edit/r2wuTE5oafYeu8h3Cjio?p=preview

Answer №2

It appears that the variable payload.data.results is populated by an AJAX request. The issue you are facing is likely due to your directive being compiled before the AJAX call has been successfully completed. To resolve this, you should set up a watch in your controller to capture the updated value once the data is returned from the AJAX call.

function DisplayListLinkFunc(scope, elem, attr) {
    console.log(scope.test123);

    scope.$watch('test123', function(newValue) {
         if (newValue) {
            console.log('The users in the directive have been updated', newValue);
         }
    });
}

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

Ensuring Consistent Height for Bootstrap Card Headers

I am currently working with bootstrap cards on two different web pages. The challenge I am facing is that on one page, the header text has a fixed height so I can easily match their card-header height using min-height. However, on the second page, the card ...

The cause of Interface A improperly extending Interface B errors in Typescript

Why does extending an interface by adding more properties make it non-assignable to a function accepting the base interface type? Shouldn't the overriding interface always have the properties that the function expects from the Base interface type? Th ...

jQuery introduces additional elements while parsing HTML code

If you have an HTML string that needs manipulation using jQuery, you may encounter the issue of jQuery adding additional tags to the string. To avoid this problem, you can follow this approach: var html = marked(input); //returns an html string console.lo ...

Transforming a cURL command into an HTTP POST request in Angular 2

I am struggling to convert this cURL command into an angular 2 post request curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic cGJob2xlOmlJelVNR3o4" -H "Origin: http://localhost:4200/form" -H "Postman-Token: fbf7ed ...

Embedding a table inside a Bootstrap popover

I'm struggling with adding a table inside a Bootstrap popover. When I click on it, the table doesn't show up. This is my first time trying to insert HTML into a popover, so I don't know the correct way to do it. Any help would be appreciated ...

Amchart 5: Tracking Cursor Movement on the X Axis

I am a beginner with amCharts5 and I am in need of assistance to retrieve the actual X value of the cursor on my chart (where the X axis represents dates). I have come across helpful examples for amCharts 4, but nothing seems to work for amCharts 5. Is thi ...

Effortlessly move and release Internet Explorer

Encountering drag and drop issues in Internet Explorer and Safari, while functioning correctly in Firefox 15 (untested on other versions). Dragging and dropping items between dropzones works in Safari, but sorting does not. In Internet Explorer, nothing wo ...

Is there another method to retrieve event.target from a React functional component?

Currently, I am creating a form and obtaining input from a mui textfield. I have successfully stored the value of the textfield to a value object. To handle the key and value of the form fields, I have implemented an onValueChanged function. My goal is to ...

Is it possible to access the chrome://webrtc-internals/ variables through an API in JavaScript?

I couldn't find any information about how to access the logged variables in chrome://webrtc-internals/ on google. There is not even a description of the graphs available there. I am specifically interested in packetsLost, googCurrentDelayMs, and goo ...

Creating an autonomous duplicate of a reversed array using JavaScript

Check out my code snippet here: http://jsfiddle.net/sepoto/Zgu9J/1/ I've started by creating a function that reverses an array: function reverseArray(input) { var reversed = new Array; for(var i = input.length-1; i >= 0; i--) { re ...

Checking phone numbers in JavaScript utilizing regular expressions while retaining the same keypress functionality

Using regular expression in JavaScript, validate a phone number with functionality similar to keypress. $('#phone').keypress(function(e) { var numbers = []; var keyPressed = e.which; for (var i = ...

Troubleshooting: CSS button animation not functioning

Attempting to create a hover animation for buttons on my webpage, I crafted the following CSS code: #B1 { margin: 50px; margin-top: 50px; margin-bottom: 50px; flex: 1 1 auto; padding: 20px; border: 2px solid #f7f7f7; text-align: center; te ...

OnsenUI: driving engagement with push notifications

Can notifications be sent from the app without relying on 'Push.send()' in the back-end? My app is straightforward - it uses a timer and I need to alert the user when the time expires, even if they are not actively using the app at that particula ...

Issue with the transmission of FormData and string data to PHP

Struggling to properly handle sending file data and string data together through ajax to PHP. Having trouble retrieving the correct string data from $_POST[] in PHP, resulting in only receiving the initial alphabet of a string instead of the specific produ ...

I am looking to display the results table on the same page after submitting a form to filter content. Can you provide guidance on how to achieve this?

Could someone provide guidance on how to approach the coding aspect of my current issue? I have a search form that includes a select form and a text box. Upon submission, a table is generated with results filtered from the form. Should I utilize a sessio ...

Choose a column in a table and organize it in ascending or descending order with the help

Does anyone know how to use JavaScript (without frameworks or plugins) to select and sort a specific column in a table? <table> <thead> <tr> <td>Col1</td> <td>Col2&l ...

How to retrieve a list of routes using axios in a Vue project set up with Webpack

I have implemented the prerender-spa-plugin in my Vue Webpack Cli project following the documentation by registering the Plugin in webpack.prod.conf.js as shown below: ... plugins: [ ... new PrerenderSpaPlugin( path.join(__dirname, '../dist&a ...

Converting lengthy timestamp for year extraction in TypeScript

I am facing a challenge with extracting the year from a date of birth value stored as a long in an object retrieved from the backend. I am using Angular 4 (TypeScript) for the frontend and I would like to convert this long value into a Date object in order ...

Sending data from a dynamically created PHP table to a modal

In my PHP-generated table, I have: <tbody> <?php $results = DB::select()->from('users')->execute(); foreach ($results as $user) { echo "<tr id='".$user['id']."'> <input type=&bs ...

Utilizing HTML data retrieved from an ajax request

I am utilizing a load more button to display content fetched from a database via ajax. Here is how the ajax call is structured: // JavaScript Document // Function to load more builds $(document).ready(function(){ var pageIndex = 1; $('#loadmorebuild ...