Accessing variables in AngularJS from one function to another function

I am facing an issue where I need to access a variable in one function from another function. My code structure is as follows:

NOTE: The value for submitData.alcohol is obtained from elsewhere in my code.

angular.module('app',['ui.router'])
 .controller('infoCtrl',['$scope','$http',functioninfoCtrl($scope,$http){
    var result;
    $scope.one = function(){
      if(submitData.alcohol=='1'){
        result = 'Yes';
      }else{
        result = 'No';
       }
    };

    $scope.two = function(){
       console.log(result);
    }
}]);

However, when I check the log, I see that the result is 'undefined'. How can I resolve this issue?

Answer №1

There may be a few reasons why this is happening:

  1. Your $scope.one function could be asynchronous, causing the console.log(result) to print undefined before $scope.one completes.
  2. It's possible that your function $scope.one is never called.

    var result = "";    
    $scope.one = function() {    
        if (submitData.alcohol == '1') {    
            result = 'Yes';
        } else {
            result = 'No';
        }        
    };
    
    $scope.two = function() {    
        $scope.one();
        console.log(result);    
    }
    

    Solution: Use Promises

Your $scope.one function can be updated like this:

$scope.one = function(param) {
  var deferred = $q.defer();

    YourAPICall(param, function(data) {            
      deferred.resolve(data);
    });    
   return deferred.promise;
};

Your $scope.two function can be updated as follows:

 $scope.two = function(){
     $scope.one(param).then(function (data) {
         console.log("data", data);//check for your condition here                  
     });
 }  

Answer №2

To ensure proper functionality, make sure to link the variable to the scope:

var $scope.output = '';

When referencing it within the if statement, use this format:

if(formData.selection=='1') {
    $scope.output = 'Approved';
} else {
    $scope.output = 'Rejected';
}

Additionally, include a console.log for debugging purposes:

console.log($scope.output);

Answer №3

Change 'result' to '$scope.result'

if (submitData.alcohol == '1') {

     $scope.result = 'Yes';
} else {

     $scope.result = 'No';
}

Another important point to note is ensuring that problem one is completed before the result is returned. It would be helpful if you can share your entire code for further analysis. Alternatively, you can provide a demonstration in plunker or jsfiddle.

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 incorporating Vue components: implementing component 2 within the template of component 1

I'm a Vue beginner and struggling with how to use one component within the template of another or how to combine them in HTML. I've tried looking through the documentation and Stack Overflow but can't seem to figure it out. Currently, I am ...

imitating an angular http call

My current issue involves a view that accesses an endpoint to transfer a resource to another user. The endpoint URL might resemble: http://mysite/api/{resource}/{Id}/transfer This operation is executed using a PUT request and the payload sent includes: ...

What is the best way to determine the width of a CSS-styled div element?

Is there a way to retrieve the width of a div element that is specified by the developer? For example, using $('body').width() in jQuery will provide the width in pixels, even if it was not explicitly set. I specifically need to access the width ...

Lifting Formik's "dirty" value/state to the parent component: A step-by-step guide

Parent Component const Mother = () => { const [dusty, setDusty] = useState(false) return ( <ChildComponent setDusty={setDusty} /> ) } Child.js ... <Formik initialValues={initialValues} onSubmit={onSubmitHandler} validationSchema={sch ...

Updating v-model with inputs is proving to be a difficult task

Creating object instances as responses can be done like this: <el-input :id="'question_' + question.id" v-model="answers[question.id]"></el-input> When entering data into these inputs, the output will look something like this: Answ ...

HTML and JavaScript: Struggling to include multiple parameters in onclick event even after escaping quotes

I am struggling to correctly append an HTML div with multiple parameters in the onclick function. Despite using escaped quotes, the rendered HTML is not displaying as intended. Here is the original HTML code: $("#city-list").append("<div class='u ...

Generating dynamic strings for identifiers in JSX

Can you help me figure out how to dynamically create IDs like this? <div id="track_1"></div> <div id="track_2"></div> I tried assigning the IDs from the parent component like this: export default function Compon ...

Update the existing code to incorporate icons into the column formatting

I'm seeking assistance from someone knowledgeable in JSON or coding as this is not my area of expertise. In my sharepoint online list, I have customized the display to show different colors based on the text content in each item. Now, I am looking to ...

Send multiple values as arguments to a jQuery function

Beginner question ahead: I'm using the jquery function loadNewPicture() to upload pictures and the progress() function to track the percentage of the upload. Everything is functioning correctly. My query relates to the variables that can be passed t ...

How can I link two separate webpages upon submitting a form with a single click?

Here is a snippet of my code: <form action="register.php" method="post"> <input type="text" name="uname"> <input type="submit" > </form> Within the register.php file, there are codes for connecting to a database. I am looking ...

Use a personalized CSS class with the Kendo Dropdown Widget

Is there a way to assign a custom CSS class to the dropdown HTML container that is created when using the .kendoDropDownList() method on a <select> or <input> element? In this fiddle ( http://jsfiddle.net/lav911/n9V4N/ ) you can see the releva ...

Steps to dynamically reveal a table row within another row when clicked:

I have a table and I want to show the contents of another row inside the current row when the plus icon is clicked. I'm not sure which HTML element to use for this. Please help me figure it out. Thank you in advance. <div class="pro ...

I am experiencing an issue where my REST call is being triggered twice while using AngularJS

Why is my REST call triggering twice when I make the call from the UI? I am using Java v8 and AngularJS v1.6, here is the service: import com.project123.temp.component.ImportFileComponent; @Component @Path("project123/ImportFileService") @JsonIgnorePrope ...

Tips for obtaining the retrieved URL from an ajax call

How can I extract only the returned URL from an ajax request? I have tried implementing it like this: $.ajax({ type: "GET", dataType : "jsonp", async: false, url: $('#F ...

Tips for keeping the main section from scrolling while scrolling through the side navigation

Within my Angular application, I have implemented a sidenav and a main section. My desired behavior is to prevent any scrolling in the main section while I am scrolling in the sidenav, similar to the functionality seen on the Angular Material Design docume ...

swapping out an external CSS file in React for a new CSS file

My React app is quite large and includes four main CSS files (darkLTR, lightLTR, darkRTL, lightRTL), which may not be the most efficient setup. The templates were provided by my boss, and I was instructed to use them instead of Material UI, which I initial ...

Utilizing Javascript to Open a New Tab from Drupal

I'm attempting to trigger the opening of a new tab when a specific menu link is clicked within a Drupal website. My initial approach was to incorporate JavaScript directly into the content of the page, but unfortunately this method has not been succes ...

Navigating with Angular's router occurs before the guard is fully completed

Within my Angular 8 application, the routing file is structured as below: const myRoutes: Routes = [ {path: '', component: FirstComponent , canActivate: [RegistrationSrcdGuard]}, {path: 'FirstComponent ', component: FirstCompon ...

Input field modified upon focus

I am currently using selectize js in my section to create a select box. My goal is to make the input editable after selecting an option when it is focused on. Check out the live demo: live demo HTML <label>Single selection <select id=" ...

Choosing an element from an array in JavaScript that meets a certain criteria

How can I isolate an object from an array where the value for the "slug" key is "A"? For instance, consider the following data: var allItems = [ { "slug": "henk", "company_founded": "2008", "company_category": "Clean", ...