Incorrect scope value detected in Angular controller

I recently started learning Angular 1, and I've encountered an issue with my code:

var app = angular.module("Football", []);

app.factory("competitions", ['$http', function($http) {
  return $http.get("json/competitions.json")
  .success(function(response) {

    var data = {
      response: response,
      teams: []
    };

    for (var i = 0; i < response.length; i++) {

      $http.get("json/teams.json")
      .success(function(response2) {
        data.teams.push(response2);
        return data
      })
      .error(function(err) {
        return err;
      });
    }

  })
  .error(function(err) {
    return err;
  });
}]);


app.controller('MainController', ['$scope', "competitions", function($scope, competitions) {
  competitions.success(function(data) {
    $scope.competitions = data;
  });
}]);

I am attempting to transfer the data from the competitions factory to $scope.competitions in MainController. However, only the response is being passed to the controller, which I recognize as incorrect. I'm unsure of how to rectify this mistake. Can anyone offer some assistance?

Answer ā„–1

Here are a few corrections that need to be made in your code.

  1. Avoid using the outdated .success() and .error() functions, and switch to using .then().

  2. The .success() function has four parameters, with the first one being the actual data returned. Instead of treating response as the entire response, extract the data from it when using .then().

  3. Consider utilizing the $q library to create and return your own promise within the factory. Extract this data in the controller where necessary.

  4. Avoid looping directly off of response, as it may not always be an array. It could be a wrapper containing the actual data instead.

  5. Ensure you handle the returned data and err from the teams.json promise appropriately, as they seem to be missing in your implementation.

  6. As promises can take time to resolve, consider invoking the teams.json call from the controller rather than the factory. Use a dummy placeholder inside an ng-repeat in the scope initially and replace it with the actual data once it's fetched.

Answer ā„–2

Give this a shot

    var app = angular.module("Soccer", []);

app.factory("leagues", ['$http', '$q', function ($http, $q) {
  function getLeagues(){
    return $http.get('json/leagues.json');
  }
  return {
    retrieve: function(){
      var primaryTask = $q.defer();
      getLeagues().then(function(response){
        var leagueData = {
          leagues: response.data,
          teams:[]
        }
        var tasks = [];
        for(var i=0;i<leagueData.leagues.length;i++){
          tasks.push($http.get("json/teams.json"));
        }
        $q.all(tasks).then(function(responses){
          for(var j = 0;j<responses.length;j++){
            leagueData.teams.push(responses[i]);
          }
          primaryTask.resolve(leagueData);
        }).catch(function(error){
          primaryTask.reject(error);
        })
      }).catch(function(error){
        primaryTask.reject(error);
      }) 
      return primaryTask.promise;
    }
  }
}]);


app.controller('PrimaryController', ['$scope', "leagues", function ($scope, leagues) {
  leagues.retrieve().then(function(data){
    $scope.leagues = data;
  }).catch(function(error){
    //handle error here
  })
}]);

Answer ā„–3

In order to tackle your issue effectively, my suggestion would be to initiate an initial request for the competitions, then consolidate all subsequent requests and resolve them using $q.all. Refer to this jsbin example for further clarity: http://jsbin.com/sugonifayi/1/edit?html,js,console

var app = angular.module("AngularApp", ['test']);

angular.module('test', [])
  .controller('TestController', ['$scope', 'CompetitionsService', function ($scope, CompetitionsService) {
    $scope.competitions = [];

    CompetitionsService.getCompetititons().then(function (response) {
      $scope.competitions = response;
      console.log($scope.competitions);
    });
  }])
.service('CompetitionsService', ['$q', function($q) {
    var getCompetititons = function() {

       // Insert appropriate http requests for competitions here
       return $q(function (resolve) {
         return resolve([{
           id: 1,
           competition: 'DUMMY-1'
         }, {
           id: 2,
           competition: 'DUMMY-2'
         }])
       }).then(function (competitions) {
         var promises = competitions.map(function (competition) {

           // Insert suitable http requests for teams here
           return $q(function (resolve) {
             var teamBaseName = competition.id;
             competition.teams = [teamBaseName + '1', teamBaseName + '2'];
             return resolve(competition)
           });
         });

         return $q.all(promises);
       });
    };

    return {
      getCompetititons: getCompetititons
    };
}]);

Please note that in the given code snippet, I have used placeholder data instead of actual http requests for demonstration purposes.

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

Show only the results that have identifiers matching the parameter in the URL

My goal is to filter objects based on a URL parameter gatewayId and display only those whose id matches the parameter. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector ...

Easily submit both FormData and a string in a single function call

I am trying to send data from a form (including a file input and string input) via ajax to an ASP.NET Function. When sending only files, I use the following code: function readURL() { var input = document.getElementById("fileUpload"); var files ...

Incorporate JavaScript values into an HTML form to submit them to PHP

How can I successfully POST the values of 'vkey' and 'gene+varient' when submitting a form in HTML? The values are retrieved using JS code and displayed correctly on the form, but are not being sent upon submission. <form action="ac ...

Is it advisable to encapsulate my entire Express server within a TypeScript class?

After working extensively with nodeJs, I have decided to explore developing applications in Typescript. Recently, I came across various blogs (like this one) that recommend wrapping modules and the app's entry point in a class when creating a RESTful ...

Step by step guide to verifying email addresses with Selenium WebDriver

A feature in my EXTJS application includes a page with an Email button. When this button is clicked, it generates a link to the page contents and opens the default email client with this link in the body. Upon inspecting the DOM, I found that the Email bu ...

Discover the key steps to extracting codes within a string in React or Javascript

I am currently developing an application that could potentially receive a string from the backend server. The string might look something like this: If you were to fold a piece of paper in half 50 times, its width would be three-quarters of the distance fr ...

Payload bytes do not match the expected byte values

I am facing an issue where the image data sent by the user is getting saved on the server in a corrupt state. Here is the structure of my setup: - api . index.js - methods . users.js (I have omitted unrelated files) There is a server.js outside ...

Get the username from Parse instead of using the ObjectID

When using angular and Parse for JavaScript, I have implemented a search field where an admin can input the objectid of a user to display their details. However, I would like to modify this functionality so that the admin can enter the username instead of ...

Tips for utilizing navigator.getDisplayMedia with automatic screen selection:

navigator.mediaDevices.getDisplayMedia({ audio: false, video: true }).then(gotMedia).catch(function(e) { console.log('getDisplayMedia() error: ', e); }); Triggering the above code will result in a popup like this. There is anoth ...

Troubleshooting Problems with POST Requests in ExpressJS

Currently, I am working on developing a feature in NodeJS that allows users to upload files. However, I am encountering difficulties while attempting to make a simple POST request. In my index.ejs file, I have written code that generates a form and initia ...

Sending a message from a Vue.js application to Contact Form 7 using the Wordpress REST API - a step-by-step guide

I recently added Contact-Form-7 to my WordPress admin panel, which generated an API Endpoint for me at http://localhost/wordpress/wp-json/contact-form-7/v1/contact-forms Attempting to send a POST request to this endpoint using the following code: data() ...

How can I make a clickable button or link within an anchor tag that is still able to be right-clicked?

Hey there, I'm currently working on a notification dropdown menu where each <li> contains a link or an <a> tag. I'm aiming to create something similar to Facebook's notification system. However, the challenge lies in trying to ...

Encountering the error code 'ERR_EMPTY_RESPONSE' while utilizing an AJAX-powered live search feature

My website features a live AJAX search bar that retrieves records from a MySQL database. However, when users repeatedly conduct searches by modifying the search criteria, some web browsers display an error message stating 'ERR_EMPTY_RESPONSE'. ...

Maintain fullcalendar event filtering across multiple renderings

I currently have a fullcalendar that initially displays all events. I am using a select dropdown to filter the events, which works well. However, when the calendar re-renders after moving to the next month, it shows all events again. Here is my calendar in ...

Why is it that styling <div> and <img> with a URL doesn't seem to work, even when applying the same styles?

In the example I have, I apply the same styling to an image and a div. Interestingly, the styling on the div makes the image look significantly better, while on the image itself it appears distorted. What could be causing this discrepancy? Both elements a ...

Combine a pair of select statements to utilize the RxJS store within an Angular Guard

When working on an Angular Guard, I encountered a challenge where I needed to select two fields from the ngrx store. Here is the code snippet for reference: @Injectable() export class RoleGuard implements CanActivate { constructor( public router: A ...

Program that duplicates text to clipboard upon clicking on the text

Hey there, I have a query regarding the script provided below: function copyElementText(id) { var text = document.getElementById(id).innerText; var elem = document.createElement("textarea"); document.body.appendChild(elem); ...

How can I configure my data source in Kendo UI to reference a specific item within the object returned by a JSON callback?

Currently, I am implementing KendoUI autocomplete to filter data as users type into a textbox. However, I am facing an issue with the autocomplete functionality. When I type into the field, the search begins, the service is called, and the JSON result/Cal ...

When utilizing multer for handling multipart data, hasOwnProperty appears to become undefined

Below is the code snippet I am currently working with: var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var multer = require('multer'); var user = requir ...

Customizing the initial page layout in Elm

I am new to Elm and I need help with a particular issue. Can someone provide guidance or direct me to a useful resource for solving this problem? The challenge Iā€™m facing involves editing the start page of a website by removing specific elements, as list ...