我有一个页面应该创建一个新的用户对象并将其发布到服务器。
这是html文件:
<div class="container" ng-controller="newUserCtrl">
...
<tr>
<td>Username:</td>
<td><input type="text" name="name" ng-value="user.username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="name" ng-value="user.password"></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name" ng-value="user.name"></td>
</tr>
...
</div>
这是控制器:
angular.module('module')
.controller('newUserCtrl', ['$scope', '$http', '$location',
'$state', newUserCtrl]);
function newUserCtrl($scope, $http, $location,
$state) {
$scope.user = {
usrename: null,
password: null,
name: null
};
$scope.saveNewUser = function() {
var aa = $scope.user;
$http.post('SERVICE URL', $scope.user)
.then(doSomething);
}
}
数据未绑定到$ scope.user对象的问题。我插入东西,然后在调用save methond后,我可以看到aa是initail用户对象。
我该怎么做?
此致 IDO
答案 0 :(得分:1)
将ng-value
更改为ng-model
以解决此问题。
这是一个Plunker https://plnkr.co/edit/R1kqBfzNHfkJK0fvKhgJ?p=preview
此解决方案使用$ scope https://plnkr.co/edit/Cic7We?p=preview
这种方法更清晰。
<div class="container" ng-controller="newUserCtrl as nu">
...
<tr>
<td>Username:</td>
<td><input type="text" name="name" ng-model="nu.user.username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="name" ng-model="nu.user.password"></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name" ng-model="nu.user.name"></td>
</tr>
...
</div>
angular.module('module')
.controller('newUserCtrl', ['$http', '$location',
'$state', newUserCtrl]);
function newUserCtrl($http, $location, $state) {
var vm = this;
vm.user = {
usrename: null,
password: null,
name: null
};
vm.saveNewUser = function() {
var aa = vm.user;
$http.post('SERVICE URL', vm.user)
.then(doSomething);
}
}