Why does AngularJS prevent me from assigning an array to the scope in a controller when it's inside the callback of a resource promise?

It seems that despite having the same Resource object generated by two different paths, there is inconsistency in the behavior of these objects - one path allows me to retrieve the array ['values-response']['distinct-value'] successfully, while the other returns "undefined" when I attempt to do so.

The console output below follows the use of the then() method on a promise returned by $q.all() within a service:

Resource
$promise: Object
$resolved: true
values-response: Object
>  distinct-value: Array[64]
metrics: Object
name: "term"
type: "xs:string"

Why am I unable to assign the distinct-value array to the scope for use in ng-repeat? Previously, without using a promise, I could achieve this within the callback of a $resource get() method:

$scope.topics = data['values-response']['distinct-value'];

This allowed me to utilize data-ng-repeat="topic in topics" in the template's ng-repeat.

However, upon transitioning to a promise, if I try the following:

$scope.topics = data.topics['values-response']['distinct-value'];

the console displays "undefined", even though it appears resolved based on the previous output.

Instead, I have to do:

$scope.topics = data.topics;

Then access the array in ng-repeat as shown below, which may not be optimized:

<button data-ng-repeat="topic in topics['values-response']['distinct-value'] | filter:textFilter | orderBy:browseOrder:browseDirection as resultsTopics" class="btn btn-default" type="button">

A MarkLogic REST API returns JSON. Although I don't believe it should be necessary, I tried using angular.fromJson() without success.

Below is a more comprehensive look at the code with simplified snippets:

app.factory('BrowseService', [
  '$q', '$resource',
  function($q, $resource) {
    var r = $resource('http://localhost\\:8005/LATEST/values/:facet', {
      format: 'json',
      options: 'browse'
    });
    var p1 = r.get({
      facet: 'term'
    });
    var p2 = r.get({
      facet: 'place'
    });
    var p3 = r.get({
      facet: 'person'
    });
    return $q.all({
      topics: p1,
      places: p2,
      people: p3
    });
  }
]);

app.controller('browseController', function($scope, BrowseService) {

  $scope.browseOrder = '_value';
  $scope.browseDirection = '';
  $scope.textFilter = '';
  $scope.people = [];
  $scope.places = [];
  $scope.topics = [];

  BrowseService.then(function(data) {
    $scope.topics = data.topics;
  });
});

The following code was successful prior to returning $q.all() from the factory:

Browse.get({
    facet: 'term'
  }, function(data) {
    $scope.topics = data['values-response']['distinct-value'];
  });

<button data-ng-repeat="topic in topics | filter:textFilter | orderBy:browseOrder:browseDirection as resultsTopics" class="btn btn-default" type="button">

Thank you for your assistance in advance.

Answer №1

There's a distinction in the success callback parameters between using .get/.post and .then. When using .then function(result){}, result.data is similar to result in .get/.post

Give this a try:

 BrowseService.then(function(results) {
     $scope.topics = results.data.topics;
     $scope.$apply();
 });

Also, double check for any typos or missing pieces. In your .get, you used:

 $scope.topics = data['values-response']['distinct-value'];

And in your .then:

 $scope.topics = data.topics['values-response']['distinct-value'];

Make sure you have added the topics property in the response

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

Is it possible to have a TypeScript Reducer alongside JavaScript Reducers in my combineReducers function?

export default combineReducers({ todosReducer, calculatorReducer, dateReducer, }); I've encountered a challenge while trying to incorporate TypeScript into a portion of my extensive codebase. In the code snippet above, envision the first two reducers ...

socket.io, along with their supporting servers

Can socket.io function separately from being the webserver? I prefer to utilize an external webserver, but in order for it to function properly I require /socket.io/socket.io.js. Is there a method other than duplicating[1] this file? I want to avoid comp ...

Mass Translation of Rows in Google Sheets

I'm looking to convert numerous foreign city names into Turkish =GOOGLETRANSLATE(A2:A100; "en"; "tr") However, when I use this formula for B2:B100, it only translates B2. Is there a method to translate all of them at once using a single function? ...

Updating the text input value in a database with PHP upon button click

Here is a breakdown of what has been implemented so far: The database table is named adhar_card. Below is the structure image for reference (Adhard_card_id serves as the primary key). https://i.sstatic.net/8j4m6.jpg Clicking on the verify button will cha ...

Using $scope in ng-include does not always result in the partial view being rendered

Within the internal view, I am dynamically rendering HTML using ng-include and ng-if directives. <div ng-controller="myController"> <div ng-if="myProperty == 1"> <div ng-include="'view1.html'"></div> ...

What is the process for conducting linting with nodemon?

Is it possible to utilize nodemon for linting my javascript without the use of build tools like gulp or grunt, in order to fully leverage node and npm? Nodemon's output can be piped. I am interested in using this feature for linting the changed file ...

Using the 'client-side rendering' and runtime environment variables in Next.js with the App Router

In the documentation for next.js, it's mentioned that runtime environment variables can be utilized on dynamically rendered pages. The test scenario being discussed involves a Next.js 14 project with an app router. On the page below, the environment ...

Adding a variety of data types to a MongoDB collection through Node.js

I'm currently using the Sails web framework along with Node.js and MongoDB to develop my own website. I am encountering some challenges while attempting to add a new user and input values (of different types: Number, Array, Object) to my 'users&a ...

Transient Flash of a jQuery Dropdown Menu

I'm currently developing a jQuery/CSS dropdown menu for a website, and everything is functioning well except for one issue. When navigating between sub-menu items, the text color of the selected main menu item briefly changes because of the CSS border ...

Retrieve the toggle input value to change the page view using jQuery

I'm currently working on a web photo gallery project and I am looking to incorporate a toggle input button that allows users to switch between displaying albums or all photos. To achieve this, I need to extract the value of the input using jQuery and ...

Vue.js2 - Detection of Observer in Array

A question for beginners in vue.js. I am trying to display data using the CanvasJS Library that is received via websocket. Everything works fine with the data until I introduce vue components into the mix. Let me clarify: export default { data() { r ...

Displaying PDF files on the internet without allowing them to be downloaded

How can I display PDF files on my website without allowing them to be saved or downloaded? Is there a way to prevent browsers from saving or downloading the PDF files? ...

Challenges encountered when implementing a personal library in a separate project

After updating a library I own, I seem to have encountered an issue when trying to use it in another project. However, the reason for this problem eludes me. A multitude of error logs with a similar theme are appearing: ERROR in ./node_modules/@company-na ...

Fetch a single random profile image from a Facebook user's list of friends using Javascript

I'm currently facing an issue with displaying a random profile picture of the user's friends on Facebook. I attempted to troubleshoot it myself but ended up crashing the login button and now it's not functioning properly. Can someone please ...

Preserve the visibility of a text input form while the checkbox is selected

Within my HTML code, there is a form that includes a checkbox labeled "other." When this checkbox is selected, a textbox will appear. If the user types in text and submits the form, the textbox disappears, but the checkbox remains checked (as saved in loca ...

Modify the menu class dynamically when scrolling using Angular and Bootstrap

I am a beginner in Angular and I am attempting to toggle between two Bootstrap menu classes when the page is scrolled. My goal is to keep the menu fixed at the top with a different background color (as defined in Bootstrap CSS) when the scroll is not at th ...

Tips for managing unexpected TCP disconnects?

Using Node.js, I set up both a TCP server and an HTTP server. The TCP server was intended to connect with hardware devices via TCP connection. I have 100 TCP clients that are maintaining their connections with the server. Normally, when a TCP client disc ...

How can I add text to an HTML5 SVG similar to using the HTML5 <p> tag?

I am currently working on creating dynamic rectangular boxes and I am facing some difficulties with inserting text into the shapes. The SVG text requires setting x and y coordinates in separate text tags, and doesn't have built-in width and height pro ...

Setting the title attribute for option elements in a select element that is bound to a model using AngularJs

I'm currently working on an HTML select element that is connected to an ng-model. Here's what the setup looks like: <select data-ng-model="accountType" data-ng-options="at.name for at in accountTypes"></select> This is how my accou ...

Implementing the History API to dynamically load content into a div using Ajax

On my WordPress site, I have post content that loads into a div using AJAX when a user clicks on it. Now, I'd like to update the URL for the current post without using hashes. How can I achieve this with my JavaScript? JavaScript: jQuery(docum ...