【问题标题】:Push multiple input strings to scope array, when input value changes (AngularJS)当输入值更改时,将多个输入字符串推送到范围数组(AngularJS)
【发布时间】:2018-02-02 03:10:39
【问题描述】:

我正在尝试将字符串添加到我在我的范围中定义的空数组。

$scope.playerNames = [];

数组中的元素数量可能因用户在玩家计数输入字段中键入的内容而异。

现在我有一个$watch 函数,它检查用户是增加还是减少玩家数量,并相应地为名称添加新的输入字段。对于这些输入字段中的每一个,我想在用户开始输入时将名称添加到数组中。来自输入字段的值 og 第一个玩家将被放置在索引 0 处,依此类推。

当用户减少玩家数量时,玩家名称(如果有)应该从数组中删除。

$scope.$watch('playerCount', function (newValue, oldValue) {
        if (newValue > 7) {
            alert("Can't have more than 7 players.");
            $scope.playerCount = oldValue;
        }
        else if (newValue > oldValue) { //if increment player count
            $("#playerNames").append("<input id='player" + newValue +"' type='text' class='form-control' placeholder='Enter name for player" + newValue + "'>");

        }
        else if (newValue < oldValue) { //i decrement player count
            console.log("Removing")
            $("#player" + oldValue).remove();
        }
    });

以下是 3 个玩家的表单外观示例:http://i.imgur.com/WcjzuNk.png

我是否正确地考虑了这个问题?有更好的方法吗?我不确定应该如何将生成的输入表单绑定到范围内定义的数组。

【问题讨论】:

  • 我尝试使用 for 循环来生成将每个输入框绑定到数组中的索引:ng-model="playerNames[index]"。但是当我在输入字段中输入值时,数组仍然是空的。
  • 是的,没有。还有其他人将 Angular 和 jQuery 混合在一起。人们,请停止这样做。使用 Angular 或 jQuery。以 Angular 方式或 jQuery 方式做事。你目前正试图让两个截然不同的东西一起工作,如果你成功了,它只会变得笨拙、混乱和不可维护,更不用说你必须加载两个库而不是一个。
  • 这里有一个简单的说明:删除 jQuery,或删除 Angular :) 并相应地修改您的应用程序。然后这个问题就会消失。它直接来自于你试图让非常不同的东西一起工作。
  • 您不需要使用 jQuery 选择 HTML 元素然后删除它们,当它们由 Angular 生成 时。只需告诉 Angularnot 生成它们(从数组中删除元素),它们就会消失。这就是它的工作原理。
  • 谢谢,我想我明白了。我不知道为什么我一开始没有考虑使用角度指令。

标签: javascript html angularjs arrays input


【解决方案1】:

您不必使用$scope.$watch。您可以通过使用ng-repeat 来处理与玩家数量具有相同数量值的数组。

var app = angular.module('testApp', []);
app.controller('testCtrl', function($scope) {
 $scope.player={"count":0};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="testApp" ng-controller="testCtrl">
<input type="number" ng-model="player.count"/>
    <div>
            <div ng-repeat="player in  [].constructor(player.count) track by $index">
                <input id="player{{$index+1}}" type="text" class="form-control" placeholder="Enter name for player {{$index+1}}" ng-model="player.value" />
            </div>
      </div>      
</body>

【讨论】:

  • @Leth 看到了吗?没有 jQuery。
  • 你可以避免构造函数并创建一个玩家数组并循环遍历它。玩家数组应该包含与玩家数量相同的元素。
  • 谢谢,这按预期工作。我不确定构造函数是如何工作的。我可能会为玩家制作一个单独的数组。
  • 是的,这样会更好。为了简单和懒惰地编写一个函数,我使用了构造函数,它将返回一个具有所需数量值的数组。但是您可以在输入上使用 ng-change 并调用一个函数来捕获玩家数量,然后创建一个玩家数组(可能是一个具有 name 属性的对象数组,可用于绑定 ng-model)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2015-03-30
  • 2017-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多