Utilizing AngularJS for Showcasing JSON Information Using Ng-Repeat and Ng-Factory

As a newcomer to Javascript and Angular, I am currently working on integrating AngularJS into my website. Despite watching tutorials from CodeSchool, Egghead, and others, I seem to be stuck at the very beginning.

My issue lies in retrieving JSON data from my server and displaying it on my website. Below is the code snippet I have been working on;

JS:

angular.module('nasuh',[])
.factory('MY', function($http){
     return  {
          isimler: function() {
          var alHemen;
          var url = 'http://localhost/uzak/remote.php?callback=JSON_CALLBACK';
          $http.get(url).success(function(data) {
          alHemen = data;
          });
          return alHemen;
        }
      };
    })
.controller('nbgCtrl', function($scope, $http, MY) {
         $scope.mangas = MY.isimler();  
     })

HTML:

<html ng-app = "nasuh">
<body ng-controller = "nbgCtrl">
<div class="col s12 m6 l4" ng-repeat = "manga in mangas"> -----> Want to repeat
        <div class="row">
        <div class="col s5">
            <a href="#" class="thumbnail">
            <img src="/kapaklar/{{manga.kapak}}">
            </a>
        </div>
        <div class="col s7">
           <p>{{manga.ad}}</p>

           <a href="" class="waves-effect waves-light btn"></a>

</div>
</div>
</div>

JSON:

 [{"id":"1","ad":"Naruto","yazar":"Masashi KISHIMOTO","kapak":"naruto.jpg"},
 {"id":"2","ad":"One Piece","yazar":"Eiichiro ODA","kapak":"one_piece.jpg"}]

Edit-1: I appreciate all the responses, but I believe I need to call the data in the controller like this;

  .factory('MY',
  return {
  isimler: function() {

.................................

$scope.mangas=isimler();

This approach allows me to use the data multiple times, especially when using it with the ui-router extension.

$stateProvider
.state('icerik', {
  url: "/icerik",
  templateUrl: "icerik.html"
   controller: $scope.mangas = isimler();
})

Answer №1

If I were to structure a factory, it would look like this:

angular.module('nasuh',[])
.factory('MY', function($http){
     var factory = {};
     var url = '/uzak/remote.php?callback=JSON_CALLBACK';
     //When you use MY.isimler, the $http promise is returned directly
     factory.isimler = $http.get(url);
     return factory;
    })
.controller('nbgCtrl', function($scope, MY) {
         //Handling the success of the $http call here
         MY.isimler.success(function(alHemen){
              $scope.mangas = alHemen;
         });  
     })

The issue at hand:

You should not do this

      $http.get(url).success(function(data) {
          alHemen = data;
      });
      return alHemen;

$http.get() is an asynchronous call. This means that the content within your success function will be executed later without interrupting the JS execution flow. Your return alHemen is ultimately invoked before the assignment alHemen = data

In my opinion, handling the call should be done by the controller. The factory should only expose methods for making calls. It's better to directly return the promise and let the controller handle it.

EDIT

By using ui router, you can utilize a promise in the resolve section to access it in your controller.

$stateProvider
.state('icerik', {
  url: "/icerik",
  templateUrl: "icerik.html",
  controller: "nbgCtrl",
  resolve: {
     isimler : function(MY){
        return MY.isimler;
     }
  }
})

You can then access it in your controller by injecting it like this:

.controller('nbgCtrl', function($scope, isimler) {
     $scope.mangas = isimler;  
 })

Refer to this documentation for more information on resolve.

Answer №2

One issue is that the http call is asynchronous in nature.

angular.module('nasuh',[])

    .factory('MY', function($http){
         return  {
              names: function() {
              var getNow;
              var url = 'http://localhost/remote.php?callback=JSON_CALLBACK';
              $http.get(url).success(function(data) {
              getNow = data;
              });
              return getNow; // This line executes before receiving a response.
            }
          };
        })

Angularjs provides a different approach to handle this situation. You should return a promise from the factory. For example-

.factory('MY', function($http,$q){
           var myFactory;
             myFactory.getJson= function(){
                var promise = $http
                .get('URLURLURL')
                .then(function (response) {
                    return response.data;
                },function (response) {
                    return $q.reject(response);
                });
            return promise;
    };
    return myFactory;
            });

To use this in a controller, you can do the following:

.controller('nbgCtrl', function($scope, MY) {
MY.getJson().then(function(data){
                      $scope.mangas = data;
                    });

     });

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

Personalized JSON response type for AJAX requests

Do you think it's possible to achieve this? I have an idea to create a unique dataType called "json/rows". This new dataType would parse the server output text and manipulate it in some way before passing it to the success function. What do you think ...

ObservableResolve(): Unleashing the power of RxJS5 for handling asynchronous data streams

Hey there! To dive deeper into RxJS, I thought of creating my own custom Rx operator. So here's a straightforward one that seems to be working smoothly: Rx.Observable.prototype.multiply = function (input) { const source = this; return Rx.O ...

I'm stumped as to why I'm having trouble loading JSON data into a DataFrame

Is there a way to convert the JSON "Data" section into a Pandas table easily? Below is my attempted code: import json import urllib.request import pandas url = urllib.request.urlopen('https://www.cryptocompare.com/api/data/coinlist/') json_obj ...

Linking the value of an expression to ngModel

There is a specific scenario where I need the ng-model property to bind to a value retrieved from the database as part of the business logic. To illustrate this concept, I have set up an example function TodoCtrl($scope) { $scope.field1 = "PropertyFr ...

What is the best way to extract a specific value from my JSON requests?

I need assistance in extracting a specific variable from the response after making a request. How can I access the data within my response? import requests import json url = "XXXXXX" payload = json.dumps({ "userName": "XXXXXX&q ...

Just dipping my toes into the world of backend development and diving into the intric

Hi everyone, I've been working on coding for a little over a year now and have mainly focused on frontend technologies like JavaScript, various frameworks, CSS, and HTML. Just yesterday, I encountered the notorious CORS issue with the Spotify API. Ev ...

Animate the service item with jQuery using slide toggle effect

Currently, I am working on a jQuery slide toggle functionality that involves clicking an item in one ul to toggle down the corresponding item in another ul. However, I am encountering difficulties in linking the click event to the correct id and toggling t ...

Ways to compel $scope to re-compile its contents and re-establish directive links

There is a set of elements in my class that, when requested by the user, are reset - essentially destroyed and recreated from scratch. As a result, the directive attached to that class also gets destroyed. The issue at hand is how can we prompt Angular (i. ...

What is the best way to create a scrollable Material UI modal and dialog?

Having a problem with my mui modal where the top content is getting cut off and I can't scroll up. I've tried adding the {overflow:"scroll"} property to the modal but it's not working. Here's the code snippet I'm currentl ...

Issues with using the $http call in Ionic Android builds are causing problems

Here is how I am making the call: $http.get( url, { params : { empId: $scope.empId } }).then(function(data, status){ $scope.workOrders = data.data; }, function(data, status){ $scope.message = data; }); It functions perfectly on Ch ...

Setting the base path for a statically exported NextJS app

I am in the process of developing and deploying a React / NextJS application to a Weblogic J2EE server with a specific context. While I have some experience with React, I am relatively new to NextJS. The current steps for building and verifying the app ar ...

Apply an opacity setting of 0.5 to the specific segment representing 30% of the scrollable div

I have a scrollable container for displaying messages. I would like to apply an opacity of 0.5 to the content in the top 30% of the container, as shown in this image: https://i.stack.imgur.com/NHlBN.png. However, when I tried using a background div with a ...

Leveraging AngularJs to extract IMEI information and identify NFC tap interactions

Recently, I found myself in a tough situation after being dumped. I need to figure out how to detect when a phone is tapped on an NFC tag and send the NFC tag number along with the phone's IMEI to a web server. While it may seem like a simple task, m ...

Simple Mobile-Friendly Tabs - mobile tabs are always visible

My JavaScript skills are not the best. I have been using Easy Responsive tabs and encountered an issue on the mobile version where clicking does not hide content, but only removes the "d_active" class and adds it to another element. I believe that if the ...

Unveil the Expressjs middleware within the API Client

I am currently developing a Nodejs API Client with the following simple form: //client.js function Client (appId, token) { if (!(this instanceof Client)) { return new Client(appId, token); } this._appId = appId; this._token = tok ...

Implementing authorization middleware using Express.js in Ajax

My app has a straightforward authorization middleware that functions flawlessly with regular GET and POST requests. However, when I send a POST request via AJAX, the middleware fails to redirect to a 401 page and instead bypasses it, allowing the data to b ...

Error in delete operation due to CORS in Flask API

After successfully developing a rest api in Flask and testing all api endpoints with Postman, I encountered an issue while working on an application in Javascript that consumes the resources of my api. The problem lies in consuming an endpoint that uses t ...

Steps to add new nodes to a JSON file on a server using PHP

How do I properly insert an array sent by jQuery into a nested JSON file using PHP? Currently, my PHP script either overwrites the entire file or appends the data to the end of the document, but I need it to be inserted into the existing nested structure o ...

pg-promise received an error due to an incorrect parameter being passed in for options

I have been working on transitioning my files from utilizing the pg package to the pg-promise package. Initially, everything was functioning correctly with the original pg solution I had in place. However, upon switching to pg-promise and referencing the d ...

Runtime.UnhandledPromiseRejection - Oops! Looks like we're trying to read properties of something that doesn't exist (specifically 'headers')

I'm facing an unexpected error that has left me puzzled. Let me walk you through what I am trying to accomplish: The task at hand involves fetching data from one API and then transmitting it to another. This process is executed as a background-funct ...