已更新
控制器
chitchatApp.controller('chitchatCtrl', ['$scope', function($scope) {
$scope.users = [
{'username': 'John'},
{'username': 'Dan'},
{'username': 'Judy'},
{'username': 'Michael'},
{'username': 'Rebecca'},
{'username': 'Macy'},
{'username': 'Ross'}
];
name = {'username': ''};
//name = {};
$scope.createuser = function createuser() {
$scope.users.push(name);
};
}]);
HTML
<body ng-app="chitchatApp" ng-controller="chitchatCtrl">
<!-- users that are currently log on will be here -->
<div class="users_container">
<div class="span2">
Here are the users that are currently log in
<li ng-repeat="user in users">
{{user.username}}
</li>
</div>
</div>
<form class="simple-form" ng-submit="createuser()">
Log in As:
<input type="text" ng-model="name.username">
<input type="submit"/>
</form>
</div>
</body>
这是我在角度js
中构建的表单<form class="simple-form" ng-submit="createuser()">
Log in As:
<input type="text" ng-model="name.username">
<input type="submit"/>
</form>
ng-model绑定到我的控制器中的空对象
name = {};
我也尝试将其修改为
name = {'username': ''};
我的$ scope这样的方法就像这样
$scope.createuser = function createuser() {
$scope.users.push(name);
};
$ scope.users是一个包含对象的数组,每个对象都具有&#39; username&#39;
的相同属性我正在使用ng-repeat在用户中循环用户。
当我点击提交时,有一个新的li,但对象中的内容消失了。我没有设置数据库。它纯粹的javascript和角度js。
表单中的模型对象是否未被修改 要么 我是否成功但是它立即消失了,我注意到当我将一个物体推入一个阵列(用ng-repeat显示)然后刷新然后它消失了因为它没有持续存在?我没有设置db?
答案 0 :(得分:2)
ng-model指令绑定到 $ scope 的属性。因此,您需要使用以下命令将 name 变量作为该范围的一部分:
$scope.name = {'username': ''};
$scope.createuser = function createuser() {
var safeCopy = angular.copy($scope.name);
$scope.users.push(safeCopy);
};
答案 1 :(得分:1)
试试这个(没有本地存储):
var app = angular.module('myapp', []);
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.users = [
{
'username': 'John'
}, {
'username': 'Dan'
}, {
'username': 'Judy'
}, {
'username': 'Michael'
}, {
'username': 'Rebecca'
}, {
'username': 'Macy'
}, {
'username': 'Ross'
}];
$scope.createuser = function createuser() {
if ($scope.name && $scope.name.username && $scope.name.username.length) {
$scope.users.push(angular.copy($scope.name));
}
$scope.name = {};
};
}]);
HTML:
<form class="simple-form" ng-submit="createuser()">Log in As:
<input type="text" ng-model="name.username" />
<input type="submit" />
</form>