Having trouble with AngularJs 1 functionality?

Having trouble fetching data from a JSON file. I've tried all available options, but nothing seems to be working. Not sure if I need to import something else. The JSON file is located at the same level as the index file. Any help would be much appreciated.

appClients.js

(function(){
    var app = angular.module('customer',[]);
    alert('Success');
    app.controller("CustomerController",function($scope,$http){
        $http.get('../customer.json')
        .success(function(data) {
           // $scope.phones = data;
           alert('Success');
        })
        .error(function(data){
            alert('Error');
        });
    });
});

index.html

<!DOCTYPE HTML>
<html ng-app="customer">
    <head>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css"  href="css/style.css">
    </head>
    <body class="Master" ng-controller="CustomerController as customer">
        <script type="text/javascript" src="js/angularjs.min.js"></script>
        <script type="text/javascript" src="js/appClients.js"></script>
        <header id="MasterHeader">

        </header>

        <div class="container">
            <div class="row">
                <div class="col-lg-12">
                    <div class="col-lg-6" id="CustomerList" ng-repeat="product in customer.clients">
                        <h3>{{product.id}}</h3>
                    </div>
                    <div class="col-lg-6" id="CustomerDetails">Details</div>
                </div>
            </div>
        </div>

        <footer id="MasterFooter">

        </footer>

    </body>
</html>

Answer №1

It seems like the IIFE (Immediately-invoked function expression) in your code is not running as expected. To resolve this issue, update your appClient.js file with the following:

(function(){
    var app = angular.module('customer',[]);
    alert('Success');
    app.controller("CustomerController",function($scope,$http){
        $http.get('../customer.json')
        .success(function(data) {
           // $scope.phones = data;
           alert('Success');
        })
        .error(function(data){
            alert('Error');
        });
    })();
})();

Make sure to pay attention to the added () in the last line of the code snippet. This adjustment should trigger the initial "Success" alert.

If the ajax call is successful, ensure that the property you assign the result to using $scope matches the one referenced in your HTML. It appears that you are setting the result to $scope.phone in the controller but referencing $scope.customer in your HTML.

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

Utilizing JavaScript to retrieve data using AJAX

Having trouble sending emails through ajax on my website. The form is in a modal (using custombox), but all values being sent are null. How can I utilize getElementById in modal content? Link to custombox git's hub: https://github.com/dixso/custombox ...

Retrieve a JSON object utilizing the spray.json library

I'm currently using a spray and I am trying to return a JSON object through a method. val route = path("all-modules") { get { respondWithMediaType(`text/html`) { complete( configViewer.findAllModules.toString) ...

When encountering an OR operator, Javascript will cease execution of the remaining conditions

This is a basic JavaScript form-validation I created. All the document.form.*.value references are present on my page, except for the document.form.dasdasdas.value ==''. In the code below, the purpose is to display an error if any of the forms a ...

The performance of my SVG Filter is dismal

Here is the SVG filter I am using: <svg style="visibility: hidden; height: 0; width: 0;"> <filter id="rgbShift"> <feOffset in="SourceGraphic" dx="1" dy="-1" result="text1" /> <feFlood flood-color="#FF0000" result=" ...

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...

Preserving the top line or heading while cutting through a table

In my HTML, I have a table with the following structure: <table id="table"> <tr> <td>ID</td> <td>Place</td> <td>Population</td> </t ...

Failure in Retrieving Fresh Information via Ajax Call

My web application utilizes polling to constantly update the status of a music player. To achieve this, I have implemented a method using setInterval to execute an Ajax call every half second. This setup functions as intended on a variety of browsers inclu ...

Tips for showing a limited number of results the first time in an AngularJS application

I am a beginner in AngularJS and Ajax requests. I created a demo where I make an Ajax request to get remote data and display it in a list. My goal is to initially show only 10 results when the page loads for the first time, and then load the next 10 result ...

Prepared SQL Statement in NodeJS for MSSQL using WHERE IN clause

I'm using the sql npm package in my Node.js project. Currently, I have an array of product SKUs like this: var skus = ['product1', 'product2', 'product3']; The SQL query stored in a file looks like this: SELECT * FROM ...

Template is not populating with data (Angular)

Currently, I am honing my Angular skills by working on a simple project. I have been seeking answers to my queries on Stack Overflow as they closely align with the issue I am facing. My challenge lies in displaying asynchronous data before it is initialize ...

Learn how to keep sessionStorage state synchronized across ReactJS components

Within my application, there is a React component responsible for displaying a list of numbers while also keeping track of the total sum of these numbers using sessionStorage. Additionally, another component provides an <input /> element to enable u ...

Tips for utilizing a variable within a variable containing HTML code

Is it possible to incorporate variables in a JavaScript function that includes HTML code? Let's consider the following example: function SetCFonts() { var Color = $('#CColor').val(); var Font = $('#CFont').val(); var S ...

Data-bind knockout select knockout bind data

Hello! I am a beginner at using knockout and I have encountered an issue with data-binds and the "option" binding. My goal is to display two drop downs populated with data from my database. Surprisingly, I have managed to get the first drop down working pe ...

Is there a way to prevent a background video from automatically playing whenever the user navigates back to the home page?

Recently, I was given a design that requires a background video to load on the home page. Although I understand that this goes against best practices, the client has approved the design and now I need to come up with a solution. The video is already in pla ...

The perplexing quandary of validating email uniqueness in AngularJS

My form in Angular needs to be able to detect duplicate user emails. The code I'm concerned about can be found here: http://plnkr.co/edit/XQeFHJTsgZONbsrxnvcI This code includes the following directives: ngFocus: tracks whether an input is on focu ...

Do we really need TypeScript project references when transpiling with Babel in an Electron project using Webpack?

Currently, I am in the process of setting up my project configuration and have not encountered any errors so far. However, based on my understanding of the Typescript documentation... It appears that Project references are not essential when using babel-l ...

What are the ideal scenarios for utilizing Dynamic encoding/decoding in Swift?

I am new to coding in Swift and I'm feeling a little confused about the concept of dynamic encoding and decoding. During an interview, I was asked to parse the response from an API. The API response looks like this: { "propertyID" : 12, "us ...

What could be the issue with my JSON file?

I am currently utilizing the jQuery function $.getJson. It is successfully sending the desired data, and the PHP script generating the JSON is functioning properly. However, I am encountering an issue at this stage. Within my $.getJSON code, my intention ...

Having trouble transmitting a file from the frontend to the server in your MERN project?

Struggling to transfer an image file from the React frontend to the server and encountering issues with sending the file: Below is the front end code snippet: useEffect(()=>{ const getImage=async ()=>{ if(file){ ...

The value of the cookie is not set (version 2.0.6 of react-cookie)

I am encountering an issue with implementing react cookies version 2. I am using webpack-dev-server for testing. Below is the console log: Warning: Failed context type: The context cookies is marked as required in withCookies(App), but its value is unde ...