Leveraging ng-repeat within ng-view

I am facing an issue with using ng-repeat inside ng-view as the data is not being displayed. I have come across suggestions on forums to use a factory, but I am hesitant to utilize a service because my $scope data relies on $routeParams for querying.

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(['$routeProvider',
function($routeProvider) {
    $routeProvider.
        when('/:name', {
            templateUrl: 'welcome.html',
            controller: 'myController'
        }).
        otherwise ({
        redirectTo: '/'
    });
}]);


myApp.controller('myController', ['$scope', '$routeParams', '$q', function($scope, $routeParams, $q) {
    var pls = users($q, $routeParams.name);
    $scope.sBP = pls;
}]);

function users($q, name) {
var playersDFD = $q.defer();
var players = new Array();
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", name);
query.find({
    success: function (results) {
        for (var i in results) {
            sPlayer = new player(results[i].get("playerName"), results[i].get("score"), results[i].get("cheatMode"));
            players.push(sPlayer);
        }
        playersDFD.resolve(players);
    },
    error: function (error) {
        alert('error');
        playersDFD.reject(data);
    }
});

return playersDFD.promise
    .then(function (results) {
        return results;
    })
    .catch(function (error) {
        alert(error.message);
    });
};

function player(name, score, cheatm){
    this.name = name;
    this.score = score;
    this.cheatm = cheatm; 
};

And here's how it should be displayed in the view:

<p ng-repeat="s in sBP">
    {{ s.name }}
</p>

Answer №1

Instead of attempting to resolve the promise within your users function, consider having it return the promise itself. This will result in cleaner and more easily understandable code, giving those using the user function the ability to control what happens once a response is received.

function users($q, name) {
    var playersDFD = $q.defer();
    var players = new Array();
    var GameScore = Parse.Object.extend("GameScore");
    var query = new Parse.Query(GameScore);
    query.equalTo("playerName", name);
    query.find({
        success: function (results) {
            for (var i in results) {
                sPlayer = new player(results[i].get("playerName"), results[i].get("score"), results[i].get("cheatMode"));
                players.push(sPlayer);
            }
            playersDFD.resolve(players);
        },
        error: function (error) {
            alert('error');
            playersDFD.reject(data);
        }
    });

    return playersDFD.promise;
}

Then utilize the users function and manage it with then.

users($q, $routeParams.name).then(function (response) {
    $scope.sBP = response;
}, function (error) {
    // handle error.
});

Additonally, I suggest separating out the users function into its own service to inject $q rather than passing it in every time.

Hope this advice proves useful.

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

Error: The JSONP request encountered an unexpected token, causing a SyntaxError

Asking for data using AJAX: $.getJSON('https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=BTC&tsym=USD&callback=?', function(result) { console.log(result); }); Encountering an error: "Uncaught SyntaxError: Unexpected token :" ...

What is the process for logging out when a different user signs in using Firebase authentication in a React Native application?

I am new to React Native and facing challenges with managing authentication state in my application. Currently, I am using Redux but have not yet implemented persistence for user login. I have incorporated Firebase authentication. Essentially, I would li ...

What is the best way to set up a property in a service that will be used by multiple components?

Here is an example of how my service is structured: export class UserService { constructor() {} coords: Coordinates; getPosition() { navigator.geolocation.getCurrentPosition(position => { this.coords = [position.coords.latitude, posit ...

Determine total and showcase it as the range slider is adjusted

Seeking to calculate and present the result of three range sliders. The equation I aim to showcase is: KM driven per year * Avg KM/100L / Price of fuel I have managed to display each slider's individual values, but I am uncertain about how to show t ...

guide to setting up router access using token

I've received a token from the backend axios.post(process.env.VUE_APP_LOGIN, payload) .then(response => { const {access_token, token_type, user} = response.data; this.token = access_token this.$store.commit(&a ...

Exploring the world of Django and JSON POSTs in the realm of Google API mania

Project Overview I am currently developing an application aimed at assisting users in finding rides. My tech stack includes Django, Python 2.7, and integration with Google Maps and Directions APIs. Within a specific view, I present a map where users can ...

Promise.all does not wait for the inner Promise.all to complete before continuing

let dataObj = [ { Id: 1, name: 'Alice', Address:[{ city: 'Paris', country: 'France' }] }, { Id: 2, name: 'Bob', Address: [{ city: 'NYC', country: &a ...

Bookshelf.js has implemented a new feature where it automatically encrypts passwords with bcrypt every time data is updated

My User Model is var Bookshelf = require('../../db').bookshelf; var bcrypt = require('bcrypt'); var Promise = require('bluebird'); var Base = require('./../helpers/base'); // Custom user model var Custom_User_Mod ...

Using Vue Router's `push()` method within an asynchronous function will solely modify the URL address

I created a custom loading component that displays while the route is being changed. To ensure the loading component properly waits for a second, the method needs to be asynchronous. However, since implementing this feature, I noticed that the router.push ...

Issue with the successful execution of connection event handler in NodeJS and Socket.io?

When I look at my code in files named server.js and index.html, I notice that the io.on('connection') part is not executing the console.log method in its callback when I visit my server in the web browser. Take a look at the code snippets below ...

Making Angular UI configuration functional

I've recently set up Angular UI, but I'm facing some issues with getting it to function properly. Here's a breakdown of the steps I took: index.html (Using Angular v1.0.1 and AngularUI v0.2.1) <script src="scripts/vendor/angular.js"> ...

Continuously calling setState within the useEffect hooks causes an infinite loop

After extensive research and reading various articles on the topic, I am still facing the issue of infinite loops with useEffect and useState. One article that caught my attention was this one. Prior to reading the article, my useState function inside use ...

PHP's json_encode function does not escape the single quote character

I am currently facing an issue with parsing a JSON encoded object in JavaScript. When I use JSON.parse(word_array);, it throws an error saying Uncaught SyntaxError: Unexpected identifier. Upon investigating, I discovered that the object word_array is miss ...

Exploring the journey of History.js and Same-Origin Policy leading to HTTPS encryption

Utilizing history.js, I am attempting to push a state change from an HTTP site like: http://www.example.com/some/resource ...to a secure site (payment page), such as: https://www.example.com/payment/for/some/resource However, Safari is throwing thi ...

Changing a string into a date format with the help of JavaScript AngularJS

My string is as follows: 13-12-2017 05:05 AM I am looking to convert it to the following format: Date 2017-12-13T05:05:00.000Z Attempted Solution: var mydate = '13-12-2017 05:05 AM'; var selectedDate = new Date(mydate); Upon logging the selec ...

Manipulating Objects and Arrays

When I retrieve data from a database query in Node.js using Postgres with Knex, I get an array of objects structured like this: (condensed version) [ { tvshow: 'house', airdate: 2017-02-01T00:00:00.000Z }, { tvshow: ' ...

How to sort multiple columns in AngularJS while keeping records 'Always on Top'?

I am currently working on a table that requires sorting, specifically by two columns (date and 'has attachment'). However, I would like to prioritize certain records (pinned) at the top of the table before sorting the rest of the rows. Html Code ...

Using Node.js to convert an array into a string and then appending slashes onto it

Currently, I am in the process of learning nodeJS. Despite trying various Stack Overflow questions and answers, I have been unable to find a solution. I have been stuck on this issue for the past two days. Here is my question: Angular JS code: $scope.q ...

The width of the table remains consistent

I have created a division that includes two tables stacked on top of each other. However, I am facing an issue where the width of the second table remains fixed and does not change even when I try to increase it. Here is the code snippet below: functio ...

The function 'create' is not a recognized property within the 'Completions' type

Recently, I've been experimenting with ChatGPT and have just installed the latest version 4.8.0. My current project is built on NextJS. Prior to this, I successfully completed a project using v3.something last month, but I'm encountering diffic ...