我想根据来自 firebase 的值更改输入字段中字体的颜色。
在 jquery 中我使用 $(document).ready() 但我的代码在 firebase 数据加载到 dom 之前触发。
我已经恢复使用 setTimeout() 来给 dom 足够的时间来加载这不是真正的方法。
必须有一个事件在数据附加到 DOM 后触发吗?
app.controller('myCtrl', function($scope, $stateParams, $firebaseObject) {
var ref = new Firebase('xxxxxxxxx');
$scope.Details = $firebaseObject(ref);
//what I really need is, "tell me when the firebase object is loaded to the DOM
//so I can do my stuff"
setTimeout(function(){
if($("#idInput").val() ==='foo'){
$("#idInput").css("color", "red");
}
}, 500);
});
最佳答案
如果您需要使用来自 $firebaseObject
的数据,请使用 $loaded()
。
$scope.Details = $firebaseObject(ref);
$scope.Details.then(function(data) {
// loaded data here
});
否则,$firebaseObject
会在数据加载后通知 $digest
循环。
另一种策略是在路由器中使用resolve
将数据加载到 Controller 中。这更简洁,因为您不需要打开 promise 。
.config(function($stateProvider) {
$stateProvider.state('home', {
controller: 'myCtrl',
template: 'myTemplate.html',
resolve: {
details: function($firebaseObject, $stateParams) {
var ref = new Firebase('xxxxxxxxx');
var childRef = ref.child($stateParams.id);
return $firebaseObject(childRef).$loaded();
}
}
});
})
然后在你的 Controller 中数据将被解析:
.controller('myCtrl', function($scope, details) {
$scope.Details = details; // totally available to use
})
Read the docs for more information on resolving data with routing and AngularFire.
关于javascript - firebase 加载到 DOM 后的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34385146/