Why aren't my Angular1.6 bindings functioning properly?

My goal is to grasp the new components, but I have a limited understanding of bindings and symbols.

Despite my efforts, I can't seem to get ng-repeat to function with this code. I've experimented with controllerAs syntax, scope, changing the bindings, and more!

APP.JS

var app = angular.module('myApp', []);

/* Mock-Data */
app.constant('friends', [{
  firstName: 'Conner',
  lastName: 'A',
  location: 'Melborne, Australia'
}, {
  firstName: 'Dom',
  lastName: 'M',
  location: 'Los Angeles, CA'
}, {
  firstName: 'Bryan',
  lastName: 'A',
  location: 'Seattle, WA'
}, {
  firstName: 'Dan',
  lastName: 'M',
  location: 'Kalispell, MO'
}]);

app.controller('HomeCtrl', ['friends', function(friends) {
  this.$onInit = function() {
    console.log("HomeCtrl has been initialized");
    this.friends = friends;
    console.log(this.friends);
  };
}]);

app.component('myGrid', {
  templateUrl: 'grid.html',
  controller: 'HomeCtrl',
  bindings: {
    data: '<' // I have tried: &,<,=,@
  }
});

Index.html

  <!DOCTYPE html>
  <html lang="en" ng-app="myApp">
  <head>
      <title>My AngularJS App</title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  </head>
  <body>

    <div class="container">

      <my-grid data="friends"></my-grid>

    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>

    <script src="app.js"></script>

  </body>

  </html>

Grid.html

  <div class="panel panel-primary">
    <div class="panel-heading">Angular 1.X - Example Component</div>
    <table class="table">
      <thead>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Location</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="employee in data">
          <td>{{ employee.firstName }}</td>
          <td>{{ employee.lastName }}</td>
          <td>{{ employee.location }}</td>
        </tr>
      </tbody>
    </table>
  </div>

Despite my best efforts, I just can't seem to make ng-repeat work..

Answer №1

You need to include a controller in index.html so that Angular knows where the friends data is coming from. Adding an ng-controller will resolve this issue.

In your component, you are using controllerAs with the alias vm, so make sure to reference it in the view as well.

index.html

<div class="container" ng-controller="HomeCtrl as ctrl">
      <my-grid data="ctrl.friends"></my-grid>
</div>

grid.html

<tr ng-repeat="employee in vm.data">

Check out the DEMO here

Answer №2

It seems like there's a small issue with your design. You forgot to pass the friends data to your directive from the parent scope. Check out this working Plunkr example for reference.

angular.module("myApp",[])
.controller('ctr1', function($scope, friends){
     $scope.friends=friends;
})
.constant('friends', [{
  firstName: 'Conner',
  lastName: 'A',
  location: 'Melborne, Australia'
}, {
  firstName: 'Dom',
  lastName: 'M',
  location: 'Los Angeles, CA'
}, {
  firstName: 'Bryan',
  lastName: 'A',
  location: 'Seattle, WA'
}, {
  firstName: 'Dan',
  lastName: 'M',
  location: 'Kalispell, MOO'
}])

.component('myGrid', {
  templateUrl: 'grid.html',
  bindings: {
    friends: '<'
  },
  controller:function() {
          this.$onInit = function() {
            console.log(this.friends);
          }
  }
  
})
<!DOCTYPE html>
<html>

<head>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9efff0f9ebf2ffecb0f4eddeafb0abb0a8">[email protected]</a>" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="myApp" ng-controller="ctr1">
  <div class="container">
    <my-grid friends="friends"></my-grid>
  </div>
</body>

</html>

<!--************************Grid.html****************
<div class="panel panel-primary">
    <div class="panel-heading">Angular 1.X - Example Component</div>
    <table class="table">
      <thead>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Location</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="employee in $ctrl.friends">
          <td>{{ employee.firstName }}</td>
          <td>{{ employee.lastName }}</td>
          <td>{{ employee.location }}</td>
        </tr>
      </tbody>
    </table>
  </div>

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

Default modal overlay closure malfunctioning; encountering errors when manually managed through jQuery

A custom overlay has been designed and implemented. <div class="overlay modal" id="11"> <div class="background-overlay"></div> <div class="description"> <div class="hidden-xs"> <img src=' ...

Seamless integration of Applitools with WebdriverIO

Seeking assistance to integrate Applitools with my WebdriverIO project. Find the specifications below: Node Version: v12.18.2 NPM Version: 6.14.5 WebdriverIO Version: 6.3.6 The service in my wdio file is configured as follows: services: ['selenium-s ...

Applying binary information to an image

Let's say I have an <img/>. The img is initially set with src='http://somelocation/getmypic'. Later on, there might be a need to change the content of the image based on some ajax call that returns binary data. However, this decision c ...

Display Angular errors specifically when the input field is filled out and contains invalid data

I need help with toggling an error area on my form so that it only appears once there is input. It seems unnecessary for errors to show up if the user hasn't even started typing. <form name="registerForm"> <input type="email" name="email" ...

Struggling to design a responsive layout as the div on the right keeps overlapping the div on the left

I recently built a React component that consists of two columns. In the left column, there's a calendar while the right column contains some text along with an input and select field. However, I noticed that when I resize the window, the elements on ...

Encountering issues when making API calls from a .NET program

I'm encountering an error when trying to call an API from a .NET application: "Script7002:XMLhttpREQUEST:Network Error 0x80070005, Access Denied." Interestingly, I am able to get the correct response when testing the API with the "Advanced Rest Cl ...

Activate a mouse click event based on user input in a Shiny

I am currently developing a shiny app that includes a plotly sunburst chart. Once I provide the correctly formatted dataframe, I need to interact with the sunburst chart by clicking on it to "drill-down." Is there a way to replicate this mouse click act ...

Obtain JSON data using jQuery

Hey there! I am currently working on understanding how to retrieve data using json/JQuery with the code below. After storing a php variable in a json variable (var ar), I confirmed its contents through console.log, although when I used document.write it d ...

Arranging hierarchical data in JavaScript

After populating the hierarchy data, it is structured as follows: Here is a screenshot: I am looking to sort this data. Currently, I have a flat data object for rendering purposes. For example, my rendering object looks like this: renderedobjects=[ {1,. ...

What's the best way to transform createHmac function from Node.js to C#?

Here's a snippet of code in Node.js: const crypto = require('crypto') const token = crypto.createHmac('sha1', 'value'+'secretValue').update('value').digest('hex'); I am trying to convert t ...

Python/Selenium Issue: JS/AJAX Content Fails to Load when URL is Accessed

Currently, I am attempting to gather data from the following URL: The data that I am looking to extract is loaded dynamically, such as the Center Bore information. When accessing the link through a standard web browser, the content loads without any issue ...

You can easily dismiss the modal by clicking on any part of the screen, not just the button

I have a problem with my current code where I can only close a modal by clicking on a specific button. I want to modify it so that the modal can be closed by clicking anywhere on the screen. Unfortunately, as a JavaScript beginner, integrating new code sni ...

Show various forms that gather information

Upon selecting an option from the drop-down menu, a certain number of forms will be displayed with captured data. For example: Imagine owning a form with fields such as No. of Applicants, Applicant Name, Telephone, E-mail, etc... If the user selects 2 fo ...

How do I modify the height of a q-select component in Quasar?

I have been struggling to change the q-select in the quasar framework, despite numerous attempts. <q-select v-model="site1" outline dense class="selection" /> :deep(.selection .q-field__control) {font-size: 13px; width: 250px;} ...

Disabling iframe javascript timers when iframe is no longer in the user's view

Currently, I am working on a blog post that will showcase various HTML5/Javascript animations through multiple <iframe> sections. These animations utilize methods such as requestAnimationFrame() and/or setInterval(). Due to limitations within the blo ...

I'm confused as to why this is occurring even though the codes appear to be identical

this.state = { lat: null }; window.navigator.geolocation.getCurrentPosition( pos=>{ this.setState({lat:pos.coords.latitude}); }, err=>{ console.log(err); } ); There seems to be an issue where using setState inside a ...

What steps do I need to take in order to create functions that are

I have 10 functions with similar structures: function socialMedia_ajax(media){ return ajaxRequest('search/' + media + 'id', media + 'id').then( function(res) { var imgStatus = res[1].length > 0 ? "c ...

What is the method for retrieving all 'name' values within a JSON array?

I am currently working on a project using Angular and I have a JSON file. I need to extract all the 'name' values from the array. Ideally, the output should look something like this: ['Sony', 'Apple', 'Sony'] JSON: ...

Tips for resizing mesh along the global axis

Have you ever used an online 3D editor that allows you to manipulate individual meshes by moving, scaling, and rotating them? This editor utilizes custom transform controls inspired by the TransformControls code from three.js. Here is a snippet of code fro ...

Having problems getting my fixed header to work on my datatable. What could be the

Struggling to make my data table Thead sticky? I attempted using position: fixed;, top: 0; with CSS but it only worked in Firefox, not Chrome, Edge, or Opera. Here is an excerpt of my Ajax code: "stateSave": false, "orderCellsTop&quo ...