如何在AngularJS中创建字符串的Add/Remove数组

How to make an Add/Remove Array of strings in AngularJS

本文关键字:Add Remove 数组 字符串 创建 AngularJS      更新时间:2023-09-26

我需要将数据绑定到字符串数组。。我需要一系列方向。

我用这种方式进行模块化:

JS-

function ShoppingCartCtrl($scope) {
    $scope.directions = ["a", "b", "c"];
    $scope.addItem = function (item) {
        $scope.directions.push(item);
        $scope.item = "";
    };
    $scope.removeItem = function (index) {
        $scope.directions.splice(index, 1);
    };
}

HTML

<div ng-app>
    <div ng-controller="ShoppingCartCtrl">
        <br />
        <table border="1">
            <thead>
                <tr>
                    <td>directions</td>
                    <td>Remove Item</td>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="item in directions">
                    <td>
                        <input ng-model="item" />{{$index}}
                    </td>
                    <td>
                        <input type="button" value="Remove" ng-click="removeItem($index)" />
                    </td>
                </tr>
            </tbody>
        </table>
        <br />
        <table>
            <tr>
                <td>
                    <input type="text" ng-model="item" />
                </td>
                <td colspan="2">
                    <input type="Button" value="Add" ng-click="addItem(item)" />
                </td>
            </tr>
            <tr>
                <td>{{directions}}</td>
            </tr>
        </table>
    </div>
</div>

一切都按预期进行,但我有一个找不到的bug。当您尝试直接从输入中修改值时,是不允许的。你写了什么都没发生(这是通过在JSFIDDLE中发布ANGULAR的最后一个版本来解决的)

继续:现在您可以修改值,但它们不会在模型中更新。如果有人能帮我,那就太棒了!!

您可以看到它在这个jsfiddle 中工作

解决方案#1:绑定对象的属性而不是字符串

您不应该直接编辑item,而应该更新项的属性。

请参阅此处的工作示例:http://jsfiddle.net/ray3whm2/15/

如果你想了解更多信息,你应该阅读这篇文章:http://nathanleclaire.com/blog/2014/04/19/5-angularjs-antipatterns-and-pitfalls/

基本上,永远不要单独绑定属性,而是在绑定中始终有一个点,即item.name而不是item。这是由于javascript本身而非angularjs造成的限制。

解决方案2:手动更新模型

如果确实需要,实际上可以使用ng-change指令手动更新阵列。请参阅此处的工作示例:http://jsfiddle.net/ray3whm2/16/

绑定到基元时,旧版本的Angular存在问题。请参阅此SO问题

因此,首先将版本更新为Angular的新版本。

ng-repeat创建一个子作用域。因为ng-repeat="item in directions"中的item是基元(即字符串),所以<input ng-model="item">会修改子作用域。这就是为什么您看不到父对象中的更改。

解决这个问题的一种方法是创建一个对象数组,而不是字符串,以使其正常工作:

$scope.directions = [{d: "a"}, {d: "b"}, {d: "c"}];

那么你的<input>将是:

<input ng-model="item.d" />

(我想,另一种方法是使用ng-model=directions[$index],但由于某种原因,每次按键后都会失去焦点

更新:@PSL表明,如果添加track by $index

,这可以工作