如何在AngularJS中添加/删除字符串数组

时间:2014-10-22 23:03:48

标签: javascript arrays angularjs data-binding

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

我这样模仿:

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>

一切都按预期工作,但我有一个我找不到的错误。当您尝试直接从输入修改值时,您不允许。你写的并没有发生任何事情(这是通过在JSFIDDLE中提出最后一个角落来解决的)

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

您可以在此jsfiddle

中看到它正常工作

2 个答案:

答案 0 :(得分:5)

解决方案#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/

答案 1 :(得分:4)

绑定到基元时,旧版Angular存在问题。见SO question

首先将版本更新为较新版本的Angular。

ng-repeat创建子范围。由于item中的ng-repeat="item in directions"是基元(即字符串),<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),这可能会有用