AngularJS推送收藏,从收藏中显示,$watch更改

AngularJS Push in Collection, Show from Collection, $watch changes

本文关键字:收藏 watch 更改 显示 AngularJS      更新时间:2023-09-26

我使用对象ITEMS来保存数据

$scope.items = [
    {value:'title1', text: 'head1',
    value:'title2', text: 'head2',
    value:'title3', text: 'head3' }
];

当我点击"添加选项"按钮时,我需要在HTML页面中显示"值"answers"文本":

$scope.items.push(
    {
        value: 'value1',
        text: 'text1'
    }
);

我可以显示对象长度,但不能显示添加的选项。$watch($watchCollection(也不起作用。

在这个例子中,我不从输入中获取值。

在此处输入链接描述

您的$scope.items数组声明不正确。您需要在数组中的每个单独项目周围使用大括号,如下所示:

$scope.items = [
    {value:'title1', text: 'head1'},
    {value:'title2', text: 'head2'},
    {value:'title3', text: 'head3'}
];

你的指令一团糟。如果你只想在列表中显示项目,你甚至不需要创建一个新的指令。你可以这样做:

<select ng-model="selectedItem" ng-options="item.text for item in items"></select>

除了ng-model="addoText"中的打字错误外,您的文本框还可以。下面的标签应该与文本框绑定到相同的变量。

key: {{addVal}} <br>and value: {{addText}}

这将在您键入文本框时更新标签。如果你不想在添加新项目之前更新标签,那么将它们绑定到一些新变量,比如:

key: {{newVal}} <br>and value: {{newText}}

最后,您的add()函数应该如下所示:

$scope.add = function () {          
    $scope.items.push(
        {
            value: $scope.addVal,
            text: $scope.addText
        }
     );
    $scope.newVal = $scope.addVal;
    $scope.newText = $scope.addText;
};

这会将新项推送到数组,并将标签上的绑定设置为新值。你不需要$watch任何东西。

这是一个Plunker。

项目数组目前的外观存在问题。我认为你的$scope.items应该看起来像:

$scope.items = [
    {
        value: "value1",
        text: "text1"
    },
    {
        value: "value2",
        text: "text2"
    }
]

而不是全部放在一个对象中,因为当你按下时,你会创建一个新对象。

对于您的问题,调用items.value将导致未定义的。

您需要调用$scope.items中的一个对象。调用items[$scope.items.length-1]将获得添加的最新对象,这样的items[$scope.items.length-1].value和items[$scope.items.length-1].text将获得该对象中的值