将 ng 模型从视图传递到控制器角度 js

Passing ng-model from view to controller angular js

本文关键字:控制器 js ng 模型 视图      更新时间:2023-09-26

我正在尝试以这种形式的角度js将这样的值从视图传递到控制器。我不希望以这种方式对其进行硬编码。如何以适当的方式完成?

angular.module('user').controller('UsersController', ['$scope', '$stateParams', 'Users',
	function($scope, $stateParams, Orders) {
		$scope.create = function() {
			var user = new Users({
				child: [
					{ columnA: child[0].columnA, columnB: child[0].columnB, columnC: child[0].columnC },
					{ columnB: child[1].columnA, columnB: child[1].columnB, columnC: child[1].columnC },
					...
					{ columnC: child[10].columnA, columnB: child[10].columnB, columnC: child[10].columnC }
				]
			});
		}
	}
});
<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.
}

我写了一个 plunker,它演示了一种类似于你尝试使用角度练习做的事情的方法。

您会注意到,我通过使用 ng-repeat 消除了视图中的所有重复项,并使child元素的数量动态化。 我用一个空数组初始化了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 更具可读性和可维护性。