通过推送元素添加新用户

时间:2014-02-13 08:49:59

标签: javascript angularjs

这是我的静态信息:

$scope.users = {
    "Eriks": {
        "name": "Kreg",
        "surname": "Indo",
        "email": "example@example.com",
        "age" : "2",
        "tel" : "+123123 22"
    }
};

我正在添加新用户:

$scope.add = function () {
    $scope.users.push({name:$scope.newUser.name, surname:$scope.newUser.surname, email:$scope.newUser.email, age:$scope.newUser.age, tel:$scope.newUser.tel});
    $scope.newUser = "";
};

当我有不同类型的$scope.users时,它会起作用

$scope.users = [{"name":"Kreg"}...more...];

这是我的表格

<small>Name: </small> <input type="text" ng-model="newUser.name"><br/>
<small>Surname: </small> <input type="text" ng-model="newUser.surname"><br/>
<small>E-mail: </small> <input type="text" ng-model="newUser.email"><br/>
<small>Age: </small> <input type="text" ng-model="newUser.age"><br/>
<small>Telephone: </small> <input type="text" ng-model="newUser.tel"><br/>
<button ng-click="add()">add new user</button>

那么我应该在add()函数中更改什么?

1 个答案:

答案 0 :(得分:1)

您无法推送到{}之类的对象。只需设置密钥,例如$scope.users[key] = userData;

您的第二个示例有效,因为它是支持array的正确push