我正在创建一个Angular应用程序,其中表单字段根据MongoDB的数据返回来填充。为了做到这一点,我知道我正在获取对象中返回的数据并将其单独分配给$ scope。如下所示。
//Keep fields filled in for current session
$scope.fill = function(id){
var cookie = $cookies.get('sessionID');
$http.get('/data/cookie/' + cookie).success(function(data) {
$scope.personal = {name: data[0].name, address: data[0].address, phone: data[0].phone, city: data[0].city, state: data[0].state, zip: data[0].zip, email: data[0].email, marital: data[0].marital, ssn: data[0].ssn, dob: data[0].dob};
$scope.income = {occupation: data[0].income[0].occupation, salary: data[0].income[0].salary, employer_phone: data[0].income[0].employer_phone, date_employeed: data[0].income[0].date_employeed};
$scope.updated = '';
});
}
然后,我使用如下所示的ng-model在表单字段中显示该数据。
<div ng-init="fill()" class="rightsec">
<div><p>Occupation</p><input class="long" type="text" ng-model="income.occupation" placeholder="Occupation"/></div>
<div><p>Salary</p><input class="medium" ng-model="income.salary" type="text" placeholder="Salary"/></div>
<div><p>Employer Phone</p><input class="medium" ng-model="income.employer_phone" type="text" placeholder="Employer Phone"/></div>
<div><p>Date Employed</p><input class="medium" type="text" ng-model="income.date_employeed" placeholder="Date Employed"/></div>
</div>
一切都按预期工作但我想知道是否有更好的方法将数据分配到范围?我还有几个领域,我认为这是不好的做法。
答案 0 :(得分:0)
根据我的数据结构,我能够简化并做到这一点。
$scope.personal = data[0];
$scope.income = data[0].income[0];