我正在尝试将数据从服务加载到表单,但不绑定从服务/服务器加载的数据的字段值:
来自服务的数据正常,问题是在此代码中设置后,我将路由加载到我的表单但表单保留旧值,此代码在我的控制器中:
$scope.cadastro = {
email: '',
name: 'the name to put in the field',
city: ''
};
$scope.editar = function () {
myAppServices.getUserData($rootScope.uid).then(function (data) {
if (data !== null) {
$scope.cadastro = data;
$scope.cadastro.name = data.name;
$location.path('cadastro');
}
});
};
HTML表单:
<form name="myDataForm" class="form-horizontal" role="form">
<div class="form-group">
<label class="col-sm-5 control-label no-padding-right" for="email">Email</label>
<div class="col-sm-7">
<span class="block input-icon input-icon-right">
<input type="text" class="form-control" placeholder="Email" name="email" ng-model="cadastro.email" focus/>
<span ng-show="myDataForm.email.$error.email" class="help-inline">Email is not valid</span>
</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label no-padding-right" for="name">Nome Completo</label>
<div class="col-sm-7">
<span class="block input-icon input-icon-right">
<input type="text" name="name" class="form-control" placeholder="Nome" ng-model="cadastro.name" />
<small class="errorMessage" data-ng-show="myDataForm.name.$dirty && myDataForm.name.$error.required"> Informe seu nome completo.</small>
</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label no-padding-right" for="address">Cidade</label>
<div class="col-sm-7">
<span class="block input-icon input-icon-right">
<input type="text" class="form-control" placeholder="Cidade" ng-model="cadastro.city" />
</span>
</div>
</div>
<div class="form-group">
<span class="lbl col-sm-5"> </span>
<div class="col-sm-7">
<button type="submit" class="width-35 pull-right btn btn-sm btn-primary" ng-click="salvarcadastroForm(cadastro)" data-ng-disabled="myDataForm.$invalid">
<i class="fa fa-floppy-o"></i> Save
</button>
</div>
</div>
</form>
我该怎么办?
解: 在控制器的init方法中加载用户数据:
$scope.init = function () {
$scope.reset();
// if user logged then load data
if ($rootScope.uid !== undefined) {
myAppServices.getUserData($rootScope.uid).then(function (data) {
if (data !== null) {
$scope.formData = data;
}
});
}
};