【问题标题】:Get returned $scope value from ng-model从 ng-model 获取返回的 $scope 值
【发布时间】:2016-06-12 21:03:56
【问题描述】:

如何从使用 ng-model 的输入生成的对象中获取值,而不是键和值?

现在已经很接近解决这个问题了

我终于设法通过使用以下代码来防止表中的单个输入值(使用 ng-repeat)显示在每一行的每个相同位置:

<input data-ng-model="newEmail[$index]" type="text" id="newEmail"    maxlength="254" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" size="20" class="form-control" placeholder="{{user.email}}">

基本上,我需要获取从 ng-model 输入的值以在我的控制器中使用,我目前正在使用这样的控制器:

$scope.newEmail = {};

$scope.updateProfile = function (profile) {
    setTimeout(function () {
        console.log('New email is: ', $scope.newEmail);
    }, 1000);
};

我遇到的问题是它从输入框中返回一个对象为 { 1: 'whatever text is enter here' }。然后,我似乎无法从对象中获取值来更新 Firebase 中的值,因为它将键和值都写入了我要写入的 Firebase 位置。

一定有一种超级简单的方法可以从我丢失的对象中获取值吗?

【问题讨论】:

  • 尝试在对象$scope.newEmail = []中使用数组
  • 传奇!!!它很有效,而且很简单,我应该尝试使用数组 insteaf 对象!谢谢 - 请作为答案发布,我会接受!
  • 我怕说它毕竟不起作用:(。好像我点击第一行,输入一个值,点击我的按钮,我会得到这个值。但是,当我在输入框中输入后续值时,它会显示空槽..

标签: javascript jquery html angularjs firebase


【解决方案1】:

输入框不返回对象。这是因为您没有将ng-model 分配为$scope.newEmail,而是分配$scope.newEmail[$index]。这就是为什么当你得到$scope.newEmail 时你得到{1: '...'} 并且它是正确的。

我不知道你的用例是什么,但你为什么将 newEmail 初始化为一个对象而不仅仅是:

$scope.newEmail = null

然后赋值为:

ng-model="newEmail"

【讨论】:

  • 他使用$index,所以他可能使用ng-repeat
  • 感谢您的快速回复。我只尝试了 $scope.newEmail = null 并且当我登录到控制台时返回的值为空。我自己也尝试过“newEmail”,但仍然没有运气。我必须将其初始化为对象的原因是由于在之前尝试过此操作之后(现在再次尝试)以及由于我已经在输入框中预先填充了来自保存数组的占位符值的事实来自用户 {{user.email}} 的现有电子邮件。
  • 你能做一个pinkr或jsfiddle让我自己试试吗?
猜你喜欢
  • 2017-09-06
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 2015-09-26
  • 1970-01-01
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
相关资源
最近更新 更多