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

Challenges encountered with the "load" event handler when creating a Firefox Extension

I am currently troubleshooting a user interaction issue with my Firefox extension. The tasks that my extension needs to complete include: Checking certain structures on the currently viewed browser tab Making backend server calls Opening dialogs Redirect ...

Steps to display content post authentication using JWT

Utilizing Nodejs and Express for application development. Utilizing JWT for authentication. I have successfully implemented the JWT-based authentication system and tested it with Postman. However, I am facing an issue when passing the request through the ...

ReactJS is struggling to showcase an image stored in the backend folder with the help of node

As a newcomer to React.js, I am facing a challenge with displaying images fetched from a database. Each action in the data has an array of images associated with it. The issue lies in not being able to properly display these images using the image tag due ...

Error message: "The property or method you are trying to access is not defined

I had no issues with my app until I added the JavaScript, now I'm getting constant errors in the console. One of the errors I see is: Property or method "show" is not defined on the instance but referenced during render. Make sure that this proper ...

What is the best way to show a UIActivityIndicatorView while fetching JSON data asynchronously and then displaying it in a UITableView?

My task involves calling a GET API that requires a string keyword and in return provides JSON data. This data is then parsed and displayed in a UITableView. While the API call is processing, I have set up a UIActivityIndicatorView to show loading progress ...

Guide on extracting an Array from JSON in a $.ajax response

I received a JSON value that was converted from an array in the AJAX response. {"Text":"Please provide a value","Email":"Please provide a value"} My goal is to extract the response JSON and display it within a div using $(div).html(): Text-Please provid ...

JavaScript application that features an audio player complete with a dynamic progress bar and customizable tags

Looking to create a custom audio player using HTML, CSS, and JS. The player should have basic functionality like a play button and progress bar. However, I want to allow users to add tags on the progress bar of the audio file, similar to how SoundCloud&apo ...

How can we convert an NSString obtained from a web service to an NSDate in Objective C?

I attempted it as follows: cell.msgid.text=[[tableArray objectAtIndex:indexPath.row]objectForKey:@"MobileMessageMasterId"]; NSString *datefromweb= [[tableArray objectAtIndex:indexPath.row] objectForKey:@"MessageDateTime"]; NSDateFormatter *dateformatte ...

Using Vue.js within Cordova platform allows developers to create dynamic

Having trouble integrating a Vue.js app into Cordova. Everything seems to be working fine, except I'm unsure how to capture Cordova events (deviceready, pause, etc.) within my Vue application. Using the Webpack template from vue-cli. This is my file ...

bespoke HTML elements and properties

I'm currently facing some difficulties and I am unsure of how challenging it can be. I have tried following various tutorials, including those on SO and YouTube, but they all provide different approaches leaving me stuck. My goal is to create a custo ...

Displaying updated character counts in Angular directive based on various triggers

I am currently working on creating a characterCounter attribute directive specifically for input fields. My idea is to use 'ngModel' to access the length of the modelValue in ng-model, and to define a max-length within the directive's scope. ...

Using Angular UI Router to Access $scope Beyond the Scope of the UI View

Looking for a way to access $scope outside the UI view in my todo app. The structure is simple, with three panels as shown in this design For the full code, visit here I need to access the to-do detail on the third panel using $rootScope, which currently ...

`The resurgence of CERT_FindUserCertByUsage function in JavaScript`

I am currently grappling with unraveling the connection between C++ dlls and JavaScript. There is a snippet of js code that reads: cert = CERT_FindUserCertByUsage(certDB, certName.nickname,certUsageEmailSigner, true, null); where the variable cert is ini ...

What is the most effective way to obtain a customer's latitude and location by prompting them to drop a pin on Google Maps?

My Android app has an API, but on my website I'm wondering how I can retrieve a person's location by having them place a marker on a Google Map. Is there a standard method for this? I need to obtain the latitude and longitude coordinates and send ...

bespoke filter designed to conceal any negative figures

I am trying to implement a feature where a text box will display nothing if the ng-model contains a negative value. I want the ng-model to remain unchanged while ensuring that negative values are not displayed. I am looking for a custom filter to achieve t ...

Tips for preventing the creation of an element in AngularJS

When working with Angular, I encountered an issue with creating an <iframe> element only upon user interaction. Initially, I simply placed the element on the page and used the ng-if directive to bind its presence to a boolean in my model. However, I ...

Breaking Down URLs with JavaScript

I am looking to extract specific portions of a URL and here is my progress so far. <script type='text/javascript'> var query = window.location.pathname.split( '/' ); query = window.location.pathname.split( '.html' ); v ...

Encountered a MongoNetworkError while attempting to establish a connection with the server at localhost:27017. The initial connection failed due to an ECONNREFUSED error at 127.0.0.1:

Encountered a MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017 If I reinstall MongoDB, the code works fine. However, I am looking for a permanent solution. [error:MongoNetworkE ...

Accessing the first child node in JsTree

Is it possible to display only the first child of a list using the JStree plugin to create a tree? For example, if I have a list with 5 children, some of which have nested children, I am looking for a way to display only the first child of each <li> ...

`Cannot Get jQuery ScrollTop Function to Work for 2nd Element`

Having trouble with an issue. Let me explain. I implemented a scrollTop Jquery on page load that scrolls down after a delay to prompt user action. However, I'm facing a problem where another scrollTop doesn't work after clicking buttons "#b3,#b3 ...