Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 路径不可用时绑定变量_Angularjs_Firebase_Angularfire - Fatal编程技术网

Angularjs 路径不可用时绑定变量

Angularjs 路径不可用时绑定变量,angularjs,firebase,angularfire,Angularjs,Firebase,Angularfire,我正试图根据firebase良好实践将数据展平,因此我尝试创建如下函数: function get(model, id) { var path = new Firebase('my/root/url'); return $firebase(path.child(model+'/'+id)).$asObject(); }; 同时,在我的控制器中,我希望有如下内容: $scope.user = get('user', $scope.userId); 其中$scope.userId

我正试图根据firebase良好实践将数据展平,因此我尝试创建如下函数:

function get(model, id) {
    var path = new Firebase('my/root/url');
    return $firebase(path.child(model+'/'+id)).$asObject();
};
同时,在我的控制器中,我希望有如下内容:

$scope.user = get('user', $scope.userId);
其中$scope.userId正在父控制器中的某个位置设置。关键是,当脚本启动时,$scope.userId在设置之前保持未定义一段时间。如何在id未定义时将$scope.user设置为空对象,然后在设置id后将其同步


我觉得答案就像是在范围上有一个承诺,所以当它实现时,我同步对象,但还不是很确定。谢谢。

您可以查看
用户ID
变量,并在有值时启动该函数

$scope.$watch('userId', function() {
   // Each time userId change this callback will be executed
   if ($scope.userId)
      $scope.user = get('user', $scope.userId) 
})
第二种解决方案如果知道用户ID的设置位置,可以使用自定义事件:

//Execution point where the userId is initalized
$scope.userId = someValue;
$scope.$emit("userid_change",$scope.userId); // Use $broascast instead of $emit if the current scope is father of the other one


// catch the event
$scope.$on("userid_change", function(e, userId) { 
   $scope.user = get('user', userId);
})
参考资料: