2014-01-28 22 views
0

更新對象應該被修改NG-表單提交的一個空對象但

控制器

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-模型綁定到一個空對象在我的控制器

name = {}; 

我嘗試了修改到這個問題,以及

name = {'username': ''}; 

我有這樣

我$範圍的方法
$scope.createuser = function createuser() { 
     $scope.users.push(name); 
    }; 

$ scope.users是一個包含對象的數組,每個對象都具有「用戶名」相同的屬性

我使用ng-repeat循環遍歷用戶中的用戶。

當我點擊提交,有一個新的李,但對象中的內容消失。我沒有建立數據庫。它純粹的javascript和角度js。

是在沒有得到修改 或 我有沒有成功的表格模型對象,但它消失的時候了,我注意到,當我把一個對象到一個數組(顯示了NG-重複)然後刷新,然後消失因爲它不會持續?我沒有建立數據庫?

+1

請出示的控制器和HTML代碼的完整的相關部分。 – Bart

+0

@Bart ok剛剛發佈 – Jngai1297

回答

2

的NG-模型指令結合的$範圍性能。因此你需要使名稱使用範圍可變部分:

$scope.name = {'username': ''}; 

$scope.createuser = function createuser() { 
    var safeCopy = angular.copy($scope.name); 
    $scope.users.push(safeCopy); 
}; 
+0

呃?你什麼意思? http://jsfiddle.net/qwertynl/94jZJ/3/ < - 找到沒有它的作品。 – qwertynl

+0

$ scope.users.push(angular.copy($ scope.name));是必要的。否則,綁定將保持活動狀態,導致修改新插入的項目。 –

+0

@qwertynl好點。如果未定義,則錯過了關於* ng-model *隱式定義* $ scope *上的屬性的部分。 – Bart

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> 

小提琴:http://jsfiddle.net/qwertynl/AvUzd/

+0

* ng-submit *取消表單的默認提交行爲,如果沒有action屬性存在。 – Bart

+0

看我的最新資訊@Bart – qwertynl