2016-01-22 123 views
0

我想將此類視圖中的值從此視圖傳遞給此窗體的角度js中的控制器。我不希望以這種方式對其進行硬編碼。如何以適當的方式完成?將NG模型從視圖傳遞到控制器角度js

angular.module('user').controller('UsersController', ['$scope', '$stateParams', 'Users', 
 
\t function($scope, $stateParams, Orders) { 
 
\t \t $scope.create = function() { 
 
\t \t \t var user = new Users({ 
 
\t \t \t \t child: [ 
 
\t \t \t \t \t { columnA: child[0].columnA, columnB: child[0].columnB, columnC: child[0].columnC }, 
 
\t \t \t \t \t { columnB: child[1].columnA, columnB: child[1].columnB, columnC: child[1].columnC }, 
 
\t \t \t \t \t ... 
 
\t \t \t \t \t { columnC: child[10].columnA, columnB: child[10].columnB, columnC: child[10].columnC } 
 
\t \t \t \t ] 
 
\t \t \t }); 
 
\t \t } 
 
\t } 
 
});
<form data-ng-submit="create()"> 
 
    <input type="text" data-ng-model="child[0].columnA"> 
 
    <input type="text" data-ng-model="child[0].columnB"> 
 
    <input type="text" data-ng-model="child[0].columnC"> 
 

 
    <input type="text" data-ng-model="child[1].columnA"> 
 
    <input type="text" data-ng-model="child[1].columnB"> 
 
    <input type="text" data-ng-model="child[1].columnC"> 
 
    
 
    ...... 
 

 
    <input type="text" data-ng-model="child[10].columnA"> 
 
    <input type="text" data-ng-model="child[10].columnB"> 
 
    <input type="text" data-ng-model="child[10].columnC"> 
 
</form>

這將是,如果可能上面的函數執行的可重複使用的指令更好。

$scope.create = function() { 
    child: toJSON(child); 
} 

function toJSON(var a) { 
    //automatically search through the view for ng-model with child[index].columnName and change to the form above. 
} 
+0

不清楚你在問什麼。你試過用'ng-repeat'嗎? – charlietfl

+0

@charlietfl您好,我目前沒有問題。這是從視圖到控制器的用戶提交表單的後表單。在這種情況下,如何簡化控制器中的分配數據ng模型進程? – stackdisplay

+0

仍然不理解問題。你意識到'ng-model'會自動創建你已經存在的所有對象,如果它們不存在的話? – charlietfl

回答

2

我寫了一個plunker演示做類似你正在嘗試採用了棱角分明的做法做一些事情的方法之一。

您會注意到我通過使用ng-repeat消除了視圖中的所有重複,並且使得元素的數量爲動態的。我使用空數組初始化了users對象,但可以使用服務器中的數據輕鬆初始化對象。

還要注意改變爲形式立即物體反射,在create()功能意味着,您可以序列化users對象,而不是形式的值。實際上,這可能不是必需的,但是,因爲如果使用像$http這樣的角度庫,JSON的序列化將自動執行。

$scope.users = { 
    child: [{}] 
}; 
$scope.create = function() { 
    var data = angular.toJson($scope.users); 
    alert(data); 
}; 

$scope.addUser = function() { 
    $scope.users.child.push({}); 
}; 
<form ng-submit="create()"> 
    <div ng-repeat="user in users.child"> 
    <input type="text" ng-model="user.columnA"> 
    <input type="text" ng-model="user.columnB"> 
    <input type="text" ng-model="user.columnC"> 
    </div> 
    <button type="submit">Submit</button> 
</form> 
<button ng-click="addUser()">Add New User</button> 

<pre> {{users}}</pre> 

從這個主要外賣,但是,應該是在視圖和控制器一起工作以消除重複和不必要的引用。我們不再指HTML中的child[0],這使得HTML更具可讀性和可維護性。

相關問題