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
}