How to access a $scope variable in the same Angular controller function from outside the function

As a newcomer to AngularJS, I have a question about accessing my $scope variable from an outside function within the same controller. How can I achieve this? Below is the code snippet:

.controller('RekapCtrl', ['$scope', '$timeout', '$state', '$stateParams', '$firebaseArray', 'Alkitabdetail', function($scope, $timeout, $state, $stateParams, $firebaseArray, Alkitabdetail) {
    var rootRef = new Firebase('https://ayobacaalkitab.firebaseio.com/');
    var childUsers = rootRef.child('users');
    var childDate = rootRef.child('tanggal');
    var rekapId = $stateParams.rekapId;
    console.log(rekapId);
    childDate.child(rekapId).child('date').child('tanggalBaca').once('value', function(snap) {
      var snapshot = snap.val();
      $scope.tanggal = snapshot;
      console.log($scope.tanggal);
    })
    // Need to access $scope.tanggal here
}])

UPDATE I want to be able to use the data fetched from Firebase stored in $scope.tanggal for further processing within another function in the same controller.

I have tried various approaches including using $scope.$apply but none of them seem to work as it always returns undefined when trying to log $scope.tanggal outside the snapshot function.

https://i.stack.imgur.com/lcsjF.jpg

I hope this explanation clarifies my query.

ANSWER

I found a solution on How to get variable value outside angular function, as 'value' being asynchronous creates some delay. The solution involves using a callback function.

childDate.child(rekapId).child('date').child('tanggalBaca').once('value',function(snap){
        var snapshot= snap.val();
        $scope.$apply(function() {
            $scope.tanggal = snapshot;
        });
        console.log($scope.tanggal);
        myAfterFunction(); // Calling the function here
    })
function myAfterFunction(){
    console.log($scope.tanggal); // This function is triggered after being called in the snapshot function; this time $scope.tanggal has the value from Firebase
    }

Answer №1

To access it directly, simply try using console.log($scope.tanggal);. If your function is not within the angularjs scope, you can utilize $scope.$apply

childDate.child(rekapId).child('date').child('tanggalBaca').once('value',function(snap){
            var snapshot= snap.val();
     $scope.$apply(function() {
            $scope.tanggal = snapshot;
    });
            console.log($scope.tanggal);
        })

console.log($scope.tanggal);

Answer №2

I stumbled upon the solution at this link How to retrieve variable value outside angular function

Since 'value' is asynchronous and causes a delay, I devised a solution using a callback function

    childDate.child(rekapId).child('date').child('tanggalBaca').once('value',function(snap){ 
var snapshot= snap.val(); 
$scope.$apply(function() { 
$scope.tanggal = snapshot; }); 
console.log($scope.tanggal); 
myAfterFunction(); //here i call the function 
}) 

function myAfterFunction(){ 
console.log($scope.tanggal); // The function is triggered after being called in the snapshot function, now $scope.tanggal has a value from firebase 
}

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

Issue with inconsistent functionality of Socket.io

I've encountered an issue while working with multiple modules - specifically, socket.io is not functioning consistently... We have successfully implemented several 'routes' in Socket.io that work flawlessly every time! However, we are now ...

Tips for sending context in the success callback function of a jQuery AJAX request

const Box = function(){ this.parameters = {name:"rajakvk", year:2010}; Box.prototype.callJsp = function() { $.ajax({ type: "post", url: "some url", success: this.executeSuccess.bind(this), err ...

The process of running npm build is not resulting in the creation of the bundle.js file

I've read through many Q&A threads where people are facing the same issue, but I still can't figure out what's wrong with my code. When I run 'sudo npm run build', no bundle.js file is being created.** This is my code: index ...

Is NextJS Route Handler in Version 13 Really Secure?

Within my forthcoming NextJS 13 web application, I am in the process of integrating an API through route handlers to facilitate functions like user registration and login procedures. Is it considered safe when transmitting sensitive data like a user's ...

Fill in datatable with information from a JSON array if there are missing values in certain columns

My goal is to populate a datatable in JavaScript. Currently, I am able to do so, but some of the last rows have blank columns which are populated first. I attempted to fill those blank columns, and then the data populates in order. Here is an example of my ...

What is the best way to include a class in the <td> element of a dynamic table?

My goal is to sum up the values in a specific column of a dynamic table by attaching an id property to each row. I am specifically focused on assigning an id to each <td> in every row of the table. UPDATE: Although I have all 4 keys in the <td> ...

What is the best way to nest _app.js within several providers?

Is there a way to wrap my top-level page _app.js in both Redux provider and Next-auth provider? Currently, I have already wrapped it in the Next-auth provider like this: import React from "react" import { Provider } from 'next-auth/client&ap ...

Using $location in an Angular directive causes a cascade effect of repainting all other directives

I am encountering an issue with my page where multiple directives are being used: <section class="start_page page--no-vcenter"> <u-search> <u-search-form></u-search-form> <u-news-form></u-ne ...

Tips for changing input field type from "password" to "text" in Angular?

Is there a way to dynamically convert an input field with type="password" to type="text" in Angular? In my demo, I have two input fields labeled Mobile no and Re-enter mobile number. I want these fields to change to type="text" if the user inputs the same ...

Convert JSON response date format to a format specified by the user

The following code snippet is currently returning the dates for $("#dob") and $("#anniversery") as 2014-04-01T00:00:00 This is my current code: <script> $(function() { function log(message) { $("<div>").text(message).p ...

Change the font awesome class when the button is clicked

Here is the code I have in this jsfiddle. I am trying to change the font awesome icon on button click using javascript, but it doesn't seem to be working. I am new to javascript, so please pardon me if this is a silly question. HTML <button id="f ...

Mobile phone web development using HTML5

I am currently facing an issue with playing sound on mobile browsers. In my code snippet, I have the following: Response.Write("<embed height='0' width='0' src='Ses.wav' />"); While this works perfectly fine on desktop ...

Learn a valuable trick to activate CSS animation using a button - simply click on the button and watch the animation start over each time

I already know how to do this once. However, I would like the animation to restart or begin again when the user clicks on it a second time. Here is what I have: function animation() { document.getElementById('ExampleButton').className = &apo ...

Despite the fact that `ng-show="true"`, it is still hiding due to having the class `ng-hide`

I'm a beginner when it comes to AngularJS, so I may be missing a straightforward solution to my issue. The challenge I'm facing involves working on a form with two inputs - one for the number of doors and the other for the number of windows. I ha ...

Passing ngModel from controller to directive in AngularJS

I'm currently working on a project that involves a controller with an attribute directive nested inside of it. This directive requires access to the ngModel of its parent controller. For more context, feel free to check out this Plunkr. Issue at Han ...

Using JavaScript within Razor C#

I am attempting to invoke a JavaScript function from within a helper method in Razor. Here is a snippet of my code: @helper MyMethod() { for (int i = 0; i < 5; i++) { drawMe(i) } } The drawMe function is defined in an externa ...

Cloning a file input does not retain the uploaded file in the cloned input. Only the original input retains the uploaded file

Whenever I duplicate an input type file, I encounter an issue where the uploaded file from the duplicated input is also linked to the original input. It seems like the duplicate input is somehow connected to and taking files for the original one. This is ...

How can I initiate an AJAX POST request over HTTPS?

Despite my efforts, I am consistently encountering a 404 error when attempting to make an Ajax POST request. The specific error message reads: "GET 404 (Not Found)." Could this issue be related to the site's use of https? Below is the code snippet t ...

Using Gmail with Nodemailer is throwing an error: "Cannot add property 'mailer' on a string with value 'SMTP'."

I am facing an issue with sending data from a form to my Gmail account. Whenever I click the submit button, I encounter the same error message repeatedly. Despite researching various problems related to nodemailer, none of them match the specific problem t ...

Swap out the HTML tags with JavaScript code

I've been looking everywhere, but I couldn't find the answer. Here is my issue / question: I have a page from CKEDITOR with: var oldText = CKEDITOR.instances.message.getData(); So far, so good. The string looks something like this: <table ...