Angular 2从数组添加或删除项目

时间:2018-10-26 03:01:14

标签: javascript jquery angular

我在这里有这种方法:

index.html

我想做的是,如果一项被选中,则将该项目添加到数组中(这部分起作用)。现在,我正在尝试从选中的数组中删除该项,如果被选中为false(这部分不起作用)。

问题是该项目没有从数组中删除。我在做什么错了?

这是我的HTML:

<a></a>

2 个答案:

答案 0 :(得分:1)

AngularJS绑定到数组对象,并且JS中的slice函数因此创建了一个新数组,将原始数组保持原样。

您应该使用splice(注意p)来更新数组。

例如:

Private Sub TextBox1_Validating(sender As Object, e As CancelEventArgs) Handles TextBox1.Validating
    Dim value = TextBox1.Text.Trim()

    'Data is optional but must be numeric if provided.
    If value <> String.Empty AndAlso Not Double.TryParse(value, Nothing) Then
        TextBox1.SelectAll()
        TextBox1.HideSelection = False

        MessageBox.Show("If data is provided, it must be numeric", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Error)

        TextBox1.HideSelection = True
        e.Cancel = True
    End If
End Sub

Private Sub TextBox2_Validating(sender As Object, e As CancelEventArgs) Handles TextBox2.Validating
    'Data is required.
    If TextBox2.Text.Trim() = String.Empty Then
        TextBox2.SelectAll()
        TextBox2.HideSelection = False

        MessageBox.Show("Data must be provided", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Error)

        TextBox2.HideSelection = True
        e.Cancel = True
    End If
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If ValidateChildren() Then
        'The data has passed validation so it is safe to use it.
    End If
End Sub

答案 1 :(得分:1)

除了slice(不是可变选项)和splice之间的混淆之外,似乎您正在使用angular作为普通js。

使用这样的框架的整个想法是摆脱DOM检查/操纵。

您不需要重载<input name>,您可以直接调用messageSelected($event.target.checked, i.id)(也修改函数公司,提供所有需要的数据)。

更好的是,您可以使用两种方式绑定[(ngModel)]="selectedItems[i.id]"checkbox绑定到“选定项目”的地图(对象),然后只需提取true项,将此映射到数组。

或者,如果您不打算更改i对象,则可以将ngModel直接绑定到诸如[(ngModel)]="i.selected"之类的自定义属性上。

该想法是避免手动接线changegetAttribute('name')

这是一个生动的例子:https://codesandbox.io/s/rjxn1y84wm

相关问题