我使用angularfire api从firebase数据库获取控制器中的数据,并从该数据更新profile.user对象。
现在问题是当我登录到profile.html页面时登录后,数据没有在他之前在数据库中保存的字段中为该用户预先填充。
谢谢。
//The controller code is:
.controller('ProfileController', function($rootScope, $timeout, $location, authObj, fbRef) {
var profile = this;
// Check the current user
var user = authObj.$getAuth();
// If no current user send to register page
if (!user) {
$location.path('/register');
return;
}
var userRef = fbRef.child('users').child(user.uid);
(function init() {
// show the message if User moves to profile page
$rootScope.alertInfo = {
title: 'You are successfully logged in!!',
detail: 'You are still logged in',
className: 'alert alert-success'
};
// Load user info
userRef.once('value', function(snap) {
profile.user = snap.val();
if (!profile.user) {
return;
}
});
})();
profile.updateProfile = function() {
userRef.set(profile.user, function onComplete() {
// show the message if write is successful
$rootScope.alertInfo = {
title: 'Successfully saved!',
detail: 'You are still logged in',
className: 'alert alert-success'
};
});
};
})
此控制器的相应路线是:
.when('/profile', {
controller:'ProfileController as profile',
templateUrl:'view/profile.html'
})
此控制器的视图是(profile.html):
<form id="frmProfile" role="form">
<h2>Profile</h2>
<br />
<div class="form-group">
<label for="txtName">Name</label>
<input type="text" ng-model="profile.user.name" class="form-control" id="txtName" placeholder="Name" name="name" />
</div>
<div class="form-group">
<label for="ddlDino">Favorite Dinosaur</label>
<select id="ddlDino" ng-model="profile.user.favoriteDinosaur" name="favoriteDinosaur" class="form-control">
<option>None</option>
<option>Pteranodon</option>
<option>Lambeosaurus</option>
<option>Stegosaurus</option>
<option>Daspletosaurus</option>
</select>
</div>
<button type="submit" ng-click="profile.updateProfile(profile.user)" class="btn btn-primary">Update</button>
答案 0 :(得分:0)
FirebaseRef.once是异步的,而且当数据返回时,angular无法知道它应该消化。您需要在回调中添加$rootScope.$apply()
以在数据返回时更新程序。或者,建议使用AngularFire来处理此类事情。
// Load user info
userRef.once('value', function(snap) {
profile.user = snap.val();
if (!profile.user) {
return;
}
$rootScope.$apply()
});