Transferring information from the service layer to the controller

My goal is to transfer data from a service to a controller using AngularJS. Below is the code I am using:

.controller('lista',function($scope,cetrams){
    $scope.hola="This is it";

    var test;
    var testfn = function(){
        test = 'Lala';
    };

    cetrams.success(function(data){
        testfn();
        test = data;
        console.log('Inside service: '+test);
    });

    console.log('Inside controller: '+test);

})

Even though the service is functioning properly and the success function is being executed, I am unable to access the variable outside of that function within the controller's scope.

Answer №1

Do not expect the value to be available at the last line.

console.log('In the controller: '+test);

Because of the asynchronous nature of the code, the last line will be executed before the service returns with the data.

You should implement your logic in the success method or use $scope.$watch to monitor changes to the test variable.

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

Guide on combining two JSON Array objects in Nodejs

Is there a way to merge two JSON Array objects together using Node.js? I am looking to combine obj1 + obj2 in order to create a new JSON object: obj1 = [ { t: 1, d: 'AAA', v: 'yes' }, { t: 2, d: 'BBB', v: 'yes& ...

What steps should I take if the slackbot is properly functioning after being invited to the channel?

Using an OAuth2 token I am looking to automate the process of sending data from Google Sheets via Slackbot. Even though I have set up tokens and connections, I find that I still need to manually input the channel id into my script. In order to streamline ...

Is it feasible to upgrade from Angular 1.3.9 to the latest version, Angular 1.6.5?

After upgrading from angular 1.3.9 to angular 1.6.5, I encountered the following console error. Uncaught Error: [$injector:unpr] Unknown provider: $$asyncCallbackProvider <- $$asyncCallback <- $animate <- compile No changes were made to my m ...

The concept of immutability is crucial when utilizing a for-in loop to append an object to an array

Within my code, I have a nested loop structure consisting of a for of with a for in loop inside it. This setup retrieves information from a Neo4J database. By utilizing the Object.assign method, I am able to transfer a property from the fetched object into ...

What could be causing my AngularJS directive to malfunction in Edge browser?

I have encountered an issue where this code works fine in all major browsers, but Edge only shows the valid value in the DOM inspector. The page still displays the old value. Why is this happening? (function (angular, module) { 'use strict'; ...

How can I convert a string containing integers into an int[] using javascript or jQuery?

I want to create a feature that allows users to input a list of IDs in a textarea, with the option to separate them by either whitespace or commas. After the user inputs the list, I need to convert it into an int[] array but also throw an error if the str ...

Update the date format in the user interface datepicker for jHipster

Recently, I created a project using Spring Boot and Angular 1 in jHipster. As someone who is new to Angular, I encountered an issue with the date format when using the UI datepicker from https://angular-ui.github.io/bootstrap. Despite setting Spanish as th ...

dynamic variable to store user input (Meteor)

I'm still trying to grasp the concept of reactive programming in Meteor, so I have a question that may seem silly: Instead of "injecting" data using the template system as documented, can I use it to extract data? For example, if I have a textarea li ...

Integrating Cache and Resolved Promises in Angular's UI-Router: A Comprehensive Guide

I have been working on an Angular app where I used to load all data before displaying any page through the ui-router resolve. However, I found that some data was being repeated, so I decided to cache the data using localStorage. Now I'm trying to figu ...

Reset the jQuery star-rating plugin

I came across a useful plugin for star ratings called JQuery Star Rating by Daniel Upshaw. My question is, how can I reset the stars in a form using this plugin? $("#btn-reset").on('click', function() { //resetting other inputs $('#st ...

Creating a custom header in React for making AJAX requests

Need help setting header in Ajax Request using axios import React, { Component, PropTypes } from 'react' import { Link, browserHistory } from 'react-router' import { connect } from 'react-redux' import axios from 'axios& ...

Tips for incorporating numerous visible arrows into your Three.js project by utilizing the THREE.ArrowHelper functionality

edited: specifying the use of ArrowHelper I am looking to create a multitude of arrows on a 2D plane to visually represent a vector field. Typically, there are around 20,000 vectors that need to be displayed. Although I am currently using THREE.ArrowHelp ...

Angular-datatables has a scroller function that allows for easy navigation within the content of

I've been scouring the web for hours, but I can't seem to find a solution. Can someone please assist me in resolving this issue? Issue: I integrated angular-datatables within an md-tab using Angular material. Everything was running smoothly unti ...

Tips for utilizing AJAX to send two values to PHP for comparison

How can I use AJAX to compare two values (#cpassword and #password) to see if they match? I've been attempting it, but it seems like I only get the value of '#cpassword'. Here is my cpassword-check.js file: // Validate confirm password whi ...

FusionMaps XT integration with VueJs: Troubleshooting connectorClick events issue

I am experiencing some issues with events connectorClick on my VueJS processed map. When I click on the connector line in the example below, the alert function does not seem to work as expected. Vue.use(VueFusionCharts, FusionCharts); let grphMap = new ...

Can you choose the stylesheet.cssRule[] based on a class name or ID?

Currently, I am able to modify the font size by accessing the first style sheet using the following code: document.styleSheets[0].cssRules[0].style.fontSize = "16"; Here is the CSS snippet: h1 {font-size: 12} .someClass {} As the CSS file ...

How can I disable a select element in Laravel 5?

Hey everyone! Currently using Laravel 5 and trying to style the "select" class as "selectpicker". I'm facing an issue where I want to disable or hide the selected option when clicked, as I'm creating a div with the option's content right b ...

Issue with scrollIntoView in devices with a width lower than 1200px

In my Angular 5 project, I have a table where each row is generated dynamically using *ngFor and given an id based on the username. <tbody *ngFor="let User of FullTable; let i = index"> <tr id='{{User.username}}'> <th scope="r ...

What causes the URL to be undefined after making a JQuery Ajax POST request?

After performing an Ajax Post within a Profile View, I am attempting to refresh the view. Here is the code snippet: $.ajax({ url: '/Profile/Index', dataType: "html", type: "POST", data: JSON.stringify(10), success: ...

Merging Two Angular Pages within a Jhipster Application

My jhipster application is simple, generating 2 entities: Product and Category. The generated pages to list the data for these entities can be found here. Specifically, there are pages for Product and Category. If I want to create a new page that combines ...