I am facing an issue with resolving services in my AngularJS controller

Having trouble resolving the service data in AngularJS controller.

var kattaApp = angular.module('kattaApp', []).controller('kattaController', function($scope, dataFactory) {
    var promise = dataFactory.getResult().then(function(data) {
        return data;
        console.log(data);
    });
    promise.then(function(data) {
        $scope.message = data;
        console.log(data.geonames[0].countrycode);
    });
    console.log(" :'( Scope is  not working  " + $scope.message);
});
angular.module('kattaApp').factory('dataFactory', function($http, $q) {
    return {
        getResult: getResult
    };

    function getResult() {
        var deferred = $q.defer();
        $http.get('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo').success(function(data, status) {
            deferred.resolve(data);
        }).error(function(data) {
            deferred.reject(data);
        });
        return deferred.promise;
    };
});

The code above attempts to assign a value to $scope.message. The service call initially returns undefined data which later gets populated and logged in the console.

Check out my implementation on Plnkr Link

Answer №1

Your code had a few bugs, but I was able to fix it by changing

<h6>{{ message }}</h6>
to
<h6>{{ $scope.message }}</h6>
.

I believe this is the solution you were looking for:

EXAMPLE LINK

Answer №2

If you're encountering an error in the browser console that says:

:'( Scope is not working undefined

it's because the code for $scope.message is placed outside of the callback function. Move it inside the callback function to ensure you get the correct values.

One way to fix this issue is by changing your promise.then function like this:

promise.then(function(data){
     $scope.message = data.geonames[0].countrycode;
         console.log(data.geonames[0].countrycode);
         console.log("$scope.message: "+$scope.message);
  });

After making this change, you should see a message like:

$scope.message: MX

For an updated Plunker demo, click on this link.

Update:

To display the message properly, remove $scope from {{scope.message}} and use it as shown below:

<h6>{{ message}}</h6>

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

Leverage the power of integrating Power BI with Javascript to easily retrieve an

I have embarked on a mission to integrate PowerBI into my web application. Below is the code snippet that I have implemented: window.config = { instance: 'https://login.microsoftonline.com/', tenant: 'common', //COMMON OR YOU ...

Determine if an object has been submitted in a MEAN / AngularJS application

I am working with an AngularJS frontend and using Express, Node, and MongoDB on the backend. My current setup is as follows: // my data to push to the server $scope.things = [{title:"title", other properties}, {title:"title", other properties}, {titl ...

Update the value of a td element when a select option is changed in another td element within the same table row

I have a table set up as follows: Header1 | Header2 | Header3 | Header 4 | Header 5 Row 1 |<span>Some Text</span> | <select></select> Row 2 Row 3 . . . . Rows generated dynamically. My objecti ...

ng-repeat inside a directive fails to update upon adding or modifying objects in the current collection

Currently, I am facing a challenge with populating a treeview that contains objects with nested arrays. If you want to see a live example of my code and the issue I'm dealing with, check out this working plunker. Let me break down how the code is st ...

JavaScript Filtering Technique

Attempting to compose an array of names for a search output page The json arrangement looks like this: data = { "artists": [ { "artistName": "a" }, { "artistName": "b" }, { "artistName": "c" }, { "artistName": "d" }, { "artistName" ...

Unable to locate my HTML file in the view section

I have been working on setting up a MEAN app and I've encountered an issue. Everything runs smoothly without the Angular part, but as soon as I integrate Angular, I am unable to view the HTML page located in the "view" folder. Here is my server setup ...

Switching over to styled components from plain CSS using a ternary operator

Currently, I am in the process of converting my project from using regular CSS to styled components (https://styled-components.com/). So far, I have successfully converted all my other components except for one that I'm having trouble with. I've ...

Using Node.js to efficiently parse JSON data into customizable PUG templates

I have a challenge where I am parsing JSON data into elements called homeCards. To achieve this, I use Axios to request the JSON data and then utilize a for loop to cycle through it. Inside my Axios function, I extract the fields I need and store them in v ...

Utilizing jQuery to automatically populate fields in an Android WebView when loading a URL

I have been able to achieve the desired output by using the following code in JS: mWebView.loadUrl("javascript:{document.getElementsByName('emailaddress')[0].value = '"+username+"'; document.getElementsByName('password')[0].v ...

Ways to stop the location object from resetting in ReactJS when reloading the page

Currently, I am using Link to redirect and call another component. The code looks something like this: <Link to={{ pathname: "/app/" + app.appId, appDetail: { app: app } }}>> When I call the path /app/:appId, it triggers the AppDetails ...

What could be causing the invalid expression error to pop up in my Vue.js template?

I encountered an error within my vue single file component: Errors compiling template: invalid expression: Unexpected token { in {{ jobs[0].build_link }} Raw expression: v-bind:href="{{ jobs[0].build_link }}" The complete code causing the is ...

What is the best method for serving static files within a nested EJS view directory?

Assuming I have the directory structure below: |--Views/ | --partial/ | --links.ejs | |--assets/ | --css/ | --styles.css | |--server.js Code for links.ejs <link rel="stylesheet" type="text/css" href="css/forms/switches.css"& ...

What is the best way to store the dom in cache to ensure that the page remains unchanged when navigating back using the back button?

When adding models to my JavaScript application's model collection using AJAX calls, I encounter an issue where if I click on a model and go to the next page, all the loaded models disappear when I hit the back button. What is the most effective way t ...

Tips on detecting a collision between a cube mesh and the boundaries of a browser using ThreeJS

I'm a beginner in 3D games and ThreeJS. In the image above, my Mesh is located at the left boundary of the browser with a position of -1035 instead of 0. This leads me to question what exactly is the relationship between mesh.position.x in ThreeJS and ...

React - the use of nested objects in combination with useState is causing alterations to the initial

After implementing radio buttons to filter data, I noticed that when filtering nested objects, the originalData is being mutated. Consequently, selecting All again does not revert back to the original data. Can anyone explain why both filteredData and orig ...

Any ideas on how to format a date for jQuery Datepicker?

Currently, I have implemented two different datepickers on my website, but I am interested in switching to jQuery's Datepicker for a more unified solution. Here is the current format that I am sending to our backend API: However, I would prefer to i ...

Understanding the Parameters for discord.js Slash Commands

I am currently working on a calculation that involves using parameters input through a slash command. While entering the parameters works without any issues, I am facing difficulty in retrieving them. The current code is resulting in an error TypeError: ...

Display an array of objects using React within the columns of a Bootstrap grid

I am facing a challenge where I have an array of components that I need to render in separate cells. The number of elements in the array can vary, sometimes exceeding the limit of 12 cells in the Bootstrap grid system. In such cases, I need to create new r ...

What methods can be used to transfer data from mapped objects to their parent component in React?

I'm in the midst of creating a cutting-edge shopping cart application. Each item is beautifully displayed as a card component within the app. To achieve this, I've utilized mapping with dummy object data: const Home = () => { const dumm ...

sw-precache-webpack-plugin for webpack's default service worker template

When utilizing the sw-precache-webpack-plugin to create a service worker for my project, I've noticed that while all my fonts, js, and css files are stored in the cache storage, the index/html file is missing. This has resulted in it not functioning p ...