ng-model
binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
但是看看这个简单的代码here提出2个问题:
<div ng-app="myApp" ng-controller="MainCtrl">
Name: <input type="text" ng-model="ctrl.name.aaa.lalala"/><input type='button' value='done'/>
<br/><br/><br/>
<div>
Welcome, {{ctrl.name.aaa.lalala}}
</div>
</div>
<script>
function MainCtrl($scope) {}
</script>
视觉:
问题
1) 每次我更改输入值时 - 它会自动更改范围属性。我相信这就是它的工作原理。但是,如果我只想在按下按钮之后 接受数据怎么办?一种解决方案是在范围内放置一个标志:"isPressed"
但我认为这是非常错误。我如何更改我的代码来做到这一点?
2) ng-model="ctrl.name.aaa.lalala"
是怎么工作的? 我希望得到一个异常(exception)。 为什么?
因为我知道我应该这样做:
$scope.name={};
$scope.name.aaa={};
然后它就会起作用。
但它在没有预定义对象的情况下是这样工作的。我错过了什么?
最佳答案
我真的很喜欢 Khanh TO 的回答,但这里有一个不同的解决方案,当您有一个包含许多属性的表单时,您可能希望或可能不想使用这些属性来更新模型。
假设你有一个表格来更新个人的个人详细信息,其中一个人由这个模型表示:
{
firstname: 'wackford',
lastname: 'squeers',
phone: '1234 567890'
}
并且您的模型包含其中的一些:
$scope.users = [ {}, {}, {} ];
当您开始编辑用户时,您会将要编辑的用户复制到另一个范围属性,例如
$scope.userUnderEdit = angular.copy( $scope.user[0] );
如果您在 UI 上按下提交,您会将编辑后的用户复制回用户集合:
$scope.commitUserChanges = function(){
$scope.users[0] = angular.copy( $scope.usersUnderEdit );
// persist data etc.
}
如果用户取消编辑,那么只需清除 userUnderEdit:
$scope.cancelUserChanges = function(){
$scope.usersUnderEdit = null;
}
演示: Fiddle
关于javascript - AngularJS ngmodel 绑定(bind)说明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21508501/