javascript - 将 ng-model 从 View 传递到 Controller Angular js

标签 javascript angularjs

我正在尝试以这种形式的 Angular js将这样的值从 View 传递到 Controller 。我不想以这种方式对其进行硬编码。如何以正确的方式完成它?

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这演示了一种类似于您尝试使用 Angular 实践执行的操作的方法。

您会注意到,我使用 ng-repeat 消除了 View 中的所有重复,并且使 child 元素的数量动态化。我使用空数组初始化了 users 对象,但您可以使用服务器中的数据轻松初始化该对象。

另请注意,对表单的更改立即反射(reflect)在对象中,这意味着在 create() 函数中,您可以序列化users 对象,而不是表单值。然而,在实践中,这可能不是必需的,因为如果您使用像 $http 这样的 Angular 库,则会自动执行与 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>

然而,主要的收获应该是 View 和 Controller 一起工作以消除重复和不必要的引用。我们不再在 HTML 中引用 child[0],使 HTML 更具可读性和可维护性。

关于javascript - 将 ng-model 从 View 传递到 Controller Angular js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34938398/

相关文章:

javascript - 如何调试在谷歌应用脚​​本中不相等的相同字符串?

javascript - 在最后两个数字之前添加逗号并在三个数字之后保留点

javascript - Angular 的 ng include 指令不适用于预期的链接

javascript - Angular-modal-service 不显示模态

java - 缓存 REST 方法

javascript - 如何在按键时停止通过 aJax 重新发送脚本?

javascript - .change() 仅运行一次,而不是在单击时运行

javascript - 防止背景项目在模态覆盖覆盖它们时获得焦点?

javascript - 尝试在 Promise 中设置值。然后返回未定义

javascript - 将数组从 json 文件传递​​到 Angular 自定义指令