How to troubleshoot passing json data from a controller to an AngularJS directive

I recently started learning AngularJS and I'm facing an issue with passing JSON data from the controller to a directive. When I try to display the data, nothing shows up and I encounter the following errors:

1. Uncaught SyntaxError: Unexpected token } on line 29.

  1. angular.js:38 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.14/$injector/modulerr?p0=myApp&p1=Error%3A%…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A17%3A381)

I'm unsure about how to resolve these errors.

<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl"> 
  <display simo='simo'></display>
</div>

<script>
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http) {
    $http.jsonp("http://localhost/json/customer.php?callback=JSON_CALLBACK")
        .success(function (data) {
            $scope.simo = data;
            console.log($scope.simo)
        });

});

app.directive('display',function(){
    return {
        restrict: 'E',
        scope: { simo: '=' },
        template: '<li ng-repeat="x in simo">{{ x.Name + ', ' + x.Country }}</li>'
    };
});
</script>

Edit: The content of the remote file is as follows:

{
  "records": [
    {
      "Name": "Alfreds Futterkiste",
      "City": "Berlin",
      "Country": "Germany"
    },
    {
      "Name": "Ana Trujillo Emparedados y helados",
      "City": "México D.F.",
      "Country": "Mexico"
    },
    // More data entries...
    {
      "Name": "Comércio Mineiro",
      "City": "São Paulo",
      "Country": "Brazil"
    }
  ]
}

Answer №1

I think I'll try this out http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">

<script>
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http) {
    $http.jsonp("http://localhost/json/customer.php?callback=JSON_CALLBACK")
        .success(function (response) {
            $scope.simo = response.data;
            console.log($scope.simo)
        });

});

app.directive('display',function(){
    return {
        restrict: 'E',
        scope: { simo: '=' },
        template: '<li ng-repeat="x in simo">{{ x.Name + ', ' + x.Country }}</li>'
    };
});
</script>

It's important to pass the correct data to the directive from your ajax call. Make sure you're handling the response.data correctly. Remember to check if your object structure is accurate and set the flag for arrays in the $http call.

Answer №2

@PersonXYZ made a great point in the comments, highlighting an issue with the template property. To illustrate this, let's consider a scenario where we replace the HTTP backend call with static test data to ensure the code can run smoothly. Take a look at the modified example below:

<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl"> 
  <display simo='simo'></display>
</div>

<script>
  var app = angular.module('myApp', []);
  app.controller('customersCtrl', function($scope, $http) {
    $scope.simo = [{
      Name: 'Frodo',
      Country: 'The Shire'
    }, {
      Name: 'Boromir',
      Country: 'Gondor'
    }];
  });

  app.directive('display',function() {
    return {
      restrict: 'E',
      scope: { simo: '=' },
      template: '<li ng-repeat="x in simo">{{ x.Name }}, {{ x.Country }}</li>'
    };
  });
</script>

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

Creating JSON from identical user interface components

I have created a form similar to this one: https://jsfiddle.net/6vocc2yn/ that generates a JSON output like below: { "List": [ { "Id": 10, "Name": "SDB_SOLOCHALLENGE_CHALLENGE_DESC_10", "email": "<a href="/cdn-cgi/l/email-pr ...

Is this jQuery script not functioning properly?

I came across this code on jsfiddle, and I really want to incorporate it into my PHP file. However, when I tried to do so, it didn't work even though I simply copied and pasted the code without making any changes. Here is my code: <!DOCTYPE html& ...

Remove the image by clicking on the "X" icon located on the top right corner of the image

One of my tasks involves deleting an image by clicking on the "X" mark located at the top right corner of the image. To achieve this, I referred to this CSS fiddle http://jsfiddle.net/yHNEv/. Sample HTML code: <div class="img-wrap"> <span ng-c ...

personalize auto-suggestions in AngularJS

Here is a link to a custom search implementation using autocomplete in angularjs. Is it possible to modify this so that the matching starts from the first character? HTML <div ng-app='MyModule'> <div ng-controller='DefaultCtrl& ...

When an element is appended, its image height may sometimes be mistakenly reported as

I am dynamically adding divs and I need to retrieve the height and width of an image. Based on this information, I have to apply CSS to the MB-Container class. For example: if the image is portrait orientation, set container width to 100%. If it's ...

Having trouble accessing a React component class from a different component class

I just started learning reactjs and javascript. For a simple project, I'm working on creating a login and registration form. The issue I'm facing is that when a user enters their email and password and clicks 'register', instead of movi ...

Error code -4058 ENOENT indicates that the file or directory does not exist. This issue is usually caused when npm is unable to locate a specific file

Trying to start a react project on my D: drive while having node installed on the C: drive resulted in an error: D:\react> npm start npm ERR! code ENOENT npm ERR! syscall open npm ERR! path D:\react/package.json npm ERR! errno -4058 npm ERR! ...

Could use some assistance with navigating Google Analytics within a Windows 10 application built with Ionic 2

Currently utilizing Ionic 2 and Angular 2 in my project. Seeking recommendations for a reliable analytics tool that is compatible with all three mobile platforms - Windows, iOS, & Android. Google Analytics did not perform adequately with my Windows 10 app ...

Troubleshooting the issue with the htmlFor attribute

I have encountered an issue with creating radio buttons and labels using JavaScript. Despite adding the 'for' attribute in the label using 'htmlFor', it does not apply to the actual DOM Element. This results in the label not selecting t ...

How can I prevent the <br/> tag from being included on every new line when exporting data to PDF in jQuery Datatable?

I am currently working with a datatable that contains a large amount of data. Within this table, I have included 2 buttons for exporting the data in PDF and CSV formats. One of the columns within my table contains a comma-separated string, and when I expor ...

Guide to displaying xmlhttpresponse in an image format

Is it possible to convert raw image content into an image file? function reqListener () { console.log(this.responseText); } var oReq = new XMLHttpRequest(); oReq.onload = reqListener; oReq.open("POST", "http://static3.filehorse.com ...

Incorporating Framer Motion into traditional React class components (non-functional approach)

I'm encountering an issue with a simple animation using Framer Motion that functions correctly in a functional component, but fails to work in a class component. I am new to Framer Motion and here is my react code => import {motion} from 'fr ...

The use of callbacks is ineffective in addressing the asynchronous nature of

Hello everyone, I'm currently working on a weather app and I'm facing an issue with the asynchronous behavior of useState. I've come across some suggestions on Stack Overflow that using a callback in the useState function might solve the pro ...

VueJS throws an error when trying to access the 'settings' property of an undefined object

I'm encountering an issue with my basic input in a Vue component. The input should update data on change, but instead I'm getting the error message Uncaught TypeError: Cannot read property 'settings' of undefined Vue component <templ ...

Creating a Custom Rule for Checkbox Validation using jQuery

Can the jQuery Validation plugin be used to validate custom values on checkboxes, rather than just True or False? For instance: <input id="test" type="checkbox" name="test" value="something"> I am struggling to find a method that can check if &apo ...

Update the value of a scope variable directly within a controller. Subsequently making a function call

Hey there, I just want to start by saying sorry in case this question has already been asked or if it seems silly. I'm pretty new to AngularJS and have managed to overcome CORS errors, set up login via Parse, and even created an API for my app using ...

Getting the Angular component class reference within a triggered Highcharts selection event callback - what's the best approach?

It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context. In my Angular component, I'm using the Highcharts library to visualize data. W ...

I am interested in modifying the hover effect for the text letters within the material UI container when hovering over it

this is the code I am currently working with: import React, { Component } from "react"; import MobileDetect from "mobile-detect"; import { map, orderBy, flowRight as compose, isEmpty, get } from "lodash"; import { Grid, Li ...

Having trouble resolving a missing dependency warning with the useEffect React Hook in my Next.js app. Any tips on how to fix this

Currently, I'm facing the following warning: Warning: React Hook useEffect has a missing dependency: 'router'. Either include it or remove the dependency array Here is the code snippet from _app.js that seems to be causing this issue: cons ...

The XMLHTTPRequest Access-Control-Allow-Origin allows cross-origin resource sharing to

I am attempting to send a request to a PHP file. I collect the longitude and latitude from a function in the Maps API, then use AJAX to store these points in a MySQL database. Using AJAX function savePoint(latitude, longitude){ $.ajax({ ...