Is there a way for me to retrieve a $scope array that is declared within a .then() function in AngularJS?

Below is the code snippet for my controller:

 $http.get(config.url+'/api/employees-suggestion/??token=' + currentUser.token + '&filterEmployee='+ "10000191")
.then(function(response) {
    console.log(response);
       $scope.id_list = [
         {employeeName: 'Hello'},
       ];
       console.log("id_list="+$scope.id_list);
   }, function(response) {
       }
 )

I am looking to access the value of '$scope.id_list' and utilize it in an external JavaScript file (which serves as a custom directive for ionic-autocomplete). Here is the directive code:

    angular.module('autocomplete.directive', [])

 .directive('ionicAutocomplete',
    function ($ionicPopover) {
      var popoverTemplate = 
       '<ion-popover-view style="margin-top:5px">' + 
         '<ion-content>' +
             '<div class="list">' +
                '<a href="#/tab/badgeboard" class="item" ng-repeat="item in id_list | filter:inputSearch" ng-click="selectItem(item)">{{item.employeeName}}</a>' +
             '</div>' +
         '</ion-content>' +
     '</ion-popover-view>';
    return {
        restrict: 'A',
        scope: {
            params: '=ionicAutocomplete',
            inputSearch: '=ngModel'
        },
        link: function ($scope, $element, $attrs) {
            var popoverShown = false;
            var popover = null;
            $scope.id_list = $scope.params.id_list;

            //Add autocorrect="off" so the 'change' event is detected when user tap the keyboard
            $element.attr('autocorrect', 'off');


            popover = $ionicPopover.fromTemplate(popoverTemplate, {
                scope: $scope
            });
            $element.on('focus', function (e) {
                if (!popoverShown) {
                    popover.show(e);
                }
            });

            $scope.selectItem = function (item) {
                $element.val(item.display);
                popover.hide();
                $scope.params.onSelect(item);
            };
        }
    };
}

{{item.employeeName}} does not display anything in the pop-over since 'id_list' is empty.

If I add the following code outside of the .then(), everything works fine and {{item.employeeName}} displays the employee names in the pop-over:

$scope.id_list = [
    {employeeName: 'Hello'},
     ];

This is the HTML code (view) which contains an input field that triggers the drop-down pop-over:

        <input type="text" ionic-autocomplete="{id_list: id_list, onSelect:onSelect}" placeholder="Search ?" ng-model="search">

I attempted using $rootScope but was unsuccessful. Any insights on what mistake I might be making and how to resolve it?

Answer №1

Let's dive into some theory:

The result of using $http.get is known as a promise. This promise is resolved asynchronously (success) or rejected (error). In the realm of angular promises, then() requires 2 functions - one for resolving and one for rejecting.

Generally speaking, it's recommended to make $http calls within angular services (such as a "service" or a "factory", both quite similar in nature). These services can be injected into various controllers or directives for reuse.

In your specific situation:

There's a possibility that your promise is being rejected, leading to the execution of the second function specified in then(), which appears to be empty at the moment.

Start by checking this aspect first, and then reach out with any updates.

Answer №2

If you're looking for an alternative method to access the $scope.id_list in your code, consider giving this a try:

var id_list=[];

$http.get(config.url+'/api/employees-suggestion/??token=' + currentUser.token + '&filterEmployee='+ "10000191")
.then(function(response) {
    console.log(response);
       id_list = {employeeName: 'Hello'};
      id_list.push({id_list: id_list});
      console.log("id_list="+id_list);
   }, function(response) {
       }
 )

By using

$scope.id_list.push({id_list: id_list});
, you can display it in the UI.

<input type="text" ionic-autocomplete="{id_list: id_list, onSelect:onSelect}"placeholder="Search ?" ng-model="search">

Additionally, define your onSelect function like this:

$scope.onSelect = function (item) {
        console.log('item', item);

    };

Expect this setup to work smoothly for you.

Answer №3

Make sure to include $scope.$apply() right after updating your result within the callback function. This will ensure that any changes made outside of Angular's usual behavior are recognized.

Answer №4

Create a custom service utilizing $http.get

angular.module('MyApp')
  .service('customService',['$http', function ($http) {

    this.fetchData = function ( callbackFunc ) {

      $http.get('CUSTOMURL')
        .success(function (response) {
            callbackFunc(response);
        })
        .error(function (response) {
            console.log('error');
        });
    };
}]);

Inject the service into your controller and use it like this:

customService.fetchData( function (response) {
    $scope.displayResponse = 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

View saved local storage information

I have an inquiry regarding saving data using localStorage for a shopping cart feature. I am able to list the data on one page through console.log but am facing difficulties in calling the data on another page. Can anyone assist with this? The Product page ...

Navigating to the Top of the Page

I am facing an issue with my webpage that is similar to the code provided below: var btn = document.getElementById('test') test.addEventListener("click", function(){ window.scroll(0,0) }) .wrap { overflow-y: scroll; position: absolute; ...

"Learn how to implement a dropdown menu using Vue.js and Quasar on Cloud Firebase

Hey there, I'm trying to figure out how to retrieve and display a Firebase array in a dropdown using Vue js. Here's what I currently have: I've read some of your articles before, but I'm having trouble displaying the data from an array ...

The challenge of implementing dynamic table rows in Vue.js

While using Vue.js to dynamically create table rows, I encountered an issue where the price in the previous row's textbox gets cleared when adding a new row. The problem seems to be related to setting the price value only when selecting a product, but ...

Conceal a <div> element when the field is devoid of content

I have a question about hiding a div if a certain field is empty. <div class="item noborder"> <img class="full-image" image-lazy-loader="lines" image-lazy-src="{{restaurantes.fornecedor_visual_foto2}}" /> </div> Is there a way to ach ...

Angular-meteor tutorials have a method known as '/parties/insert' that is already clearly defined and explained

I am currently diving into meteor + angular and enjoying learning through ! As I was working on the 3-way data binding section, I created a folder named collections within the socially folder. In this folder, I made a file called parties.ts where I added ...

Utilize pivot to manage user roles and permissions in ExpressJS application using Mongoose

My user schema is structured as shown below const userSchema = mongoose.Schema({ username: { type: String, required: true, }, first_name: { type: String, required: true, }, last_name: { type: Stri ...

Developing a countdown timer with an initial value set by the user in an input field

Whenever I click the button, the countdown only advances by one digit before stopping. It seems that the countdown is reverting to the initial value entered in the input box. My goal is to have the initial value entered in the input field set as the starti ...

Generating multiple circles on Google Map using ng-maps

I have reviewed several similar posts on SO, but I am still struggling to figure out my mistake. My goal is to place multiple circles on a Google map using a JSON string setup like this: [ {"name":"0","lat":30.45,"long":91.15}, {"name":"1","lat": ...

Tips on adjusting the hover color in the data grid

I want to adjust the color of the Datagrid when hovering over it, does anyone know how to do this? The default color displayed is light blue, but I would like to change it to a different color. Can someone please assist me with this? Looking for document ...

Why might hashtags be effective while html5 mode fails to generate results?

If you have a link element <a href="#/sign-in">Link</a> that works well with $routeProvider in your configuration, what might prevent enabling HTML5 mode from functioning properly? Assuming you've set <base href="/"> in the head and ...

Sending an associative array to Javascript via Ajax

Learning a new programming language is always a great challenge. Can someone guide me on how to efficiently pass an associative array to JavaScript using AJAX? Below is a snippet of code from server.php: $sql = "SELECT Lng, Lat, URL FROM results LIMIT ...

The components declared in the index file are rendered on every route throughout the React application

I'm a beginner with React and I'm using react-router version 6.0.2. My issue is that I created a component for the router and then called this component in the index file. However, when I add another component to the index file, it gets rendered ...

Utilizing the toggle switch functionality in Django with a boolean field implementation

My work_experience model includes an "is_working" field which is set to true when a user is currently employed at a company. I am using a toggle switch on the front end and would like to update the boolean field value for "is_working" with a click. What lo ...

Show a popover within a parent div that has limited visible space due to its hidden overflow

Struggling with AngularJS, I can't seem to find a simple solution for this problem. In my code, there's a div element with the overflow: hidden property set due to an internal scrollbar. Inside this div, there's a dropdown menu that is trigg ...

The organization and control of metadata associated with threejs Geometry

Looking for advice on how to connect Metadata to my three.js geometries. Since there is no direct Attribute available in the Object, what would be the most effective method for linking this data? ...

What is the most effective way to extract Geolocation API co-ordinates from my nested function and store them in React state?

My goal is to retrieve a user's location once they click a button using the Geolocation API. <button onClick={this.setNewLatLong()}>"Use my location"</button>; I have successfully obtained the latitude and longitude coordinates with the ...

Is it possible to deploy Vue.js from a content delivery network (CDN) for production

My decision to use Vue.js for a new project was influenced by its ability to run natively in the browser, unlike React which requires compilation/transpilation via Node. I'm considering linking directly to a CDN like this in my production code: <s ...

Differences between the scope of if statements in JavaScript and Python

I have a function in React where I am trying to achieve the following: renderPost(data) { const dateStr = new Date(data.pub_date).toLocaleString(); let img='empty'; if (data.header_image_url.url !== null) { ...

The Vue v-model-bound HTML element is unable to update the Vue instance when a different JavaScript entity binds to it and modifies the data

In my project, I have implemented Vue.js for two-way data binding on a remote control alarm clock. The main code can be found here. You can access the running instance of the server here. While most of the page uses Vue and JavaScript for rendering, I de ...