在同一个控制器角度

时间:2016-09-08 10:26:40

标签: javascript angularjs firebase firebase-realtime-database

我是AngularJS的新手,我想知道如何从同一控制器内部的外部函数访问我的$scope变量。怎么做到这一点?这是我的代码:

.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);
    })
    // here outside function i want to access my $scope.tanggal;
}])

更新 我想要实现的是我可以使用来自$ scope.tanggal里面的firebase的结果来处理同一控制器中的另一个函数。

我尝试了很多东西,包括使用$ scope。$ apply但是当我在快照函数之外尝试console.log $ scope.tanggal时,它总是返回undefined。

enter image description here

希望这能让你理解我的问题。

ANSWER

我在这里找到了答案 How to get variable value outside angular 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 called in snapshot function this time $scope.tanggal has value from firebase
    }

2 个答案:

答案 0 :(得分:1)

您可以直接访问它,只需尝试NSData, 如果您的函数不在angularjs范围内,则可以使用console.log($scope.tanggal);

$scope.$apply

答案 1 :(得分:0)

我在这里找到了答案 How to get variable value outside angular function

因为'value'是异步的并且会产生一些延迟,所以我使用回归函数来提供解决方案

    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 called in snapshot function this time $scope.tanggal has value from firebase 
}
相关问题