Javascript AngularJS推入集合,从集合显示,$watch更改
我使用对象项来保存数据Javascript AngularJS推入集合,从集合显示,$watch更改,javascript,html,angularjs,Javascript,Html,Angularjs,我使用对象项来保存数据 $scope.items = [ {value:'title1', text: 'head1', value:'title2', text: 'head2', value:'title3', text: 'head3' } ]; 当我单击“添加选项”按钮时,我需要在HTML页面中显示“值”和“文本”: $scope.items.push( { value: 'value1', text: 'text1'
$scope.items = [
{value:'title1', text: 'head1',
value:'title2', text: 'head2',
value:'title3', text: 'head3' }
];
当我单击“添加选项”按钮时,我需要在HTML页面中显示“值”和“文本”:
$scope.items.push(
{
value: 'value1',
text: 'text1'
}
);
我可以显示对象长度,但不能显示添加的选项。
$watch$watchCollection也不起作用
在本例中,我不从输入中获取值
您的items数组目前的外观存在问题。 我认为您的$scope.items应该如下所示:
$scope.items = [
{
value: "value1",
text: "text1"
},
{
value: "value2",
text: "text2"
}
]
而不是全部放在一个对象中,因为当您按下按钮时,您将创建一个新对象
对于您的问题,调用items.value将导致未定义的错误
您需要调用$scope.items中的对象。调用项[$scope.items.length-1]将添加最新的对象,并且这些项[$scope.items.length-1].value和项[$scope.items.length-1]。将该对象中的值设置为文本。您的$scope.items数组声明不正确。数组中的每个单独项都需要大括号,如下所示:
$scope.items = [
{value:'title1', text: 'head1'},
{value:'title2', text: 'head2'},
{value:'title3', text: 'head3'}
];
key: {{newVal}} <br>and value: {{newText}}
$scope.add = function () {
$scope.items.push(
{
value: $scope.addVal,
text: $scope.addText
}
);
$scope.newVal = $scope.addVal;
$scope.newText = $scope.addText;
};
你的指令乱七八糟。如果只想在列表中显示项目,甚至不需要创建新指令。您可以这样做:
<select ng-model="selectedItem" ng-options="item.text for item in items"></select>
这将在您键入文本框时更新标签。如果在添加新项之前不想更新标签,请将其绑定到一些新变量,如下所示:
$scope.items = [
{value:'title1', text: 'head1'},
{value:'title2', text: 'head2'},
{value:'title3', text: 'head3'}
];
key: {{newVal}} <br>and value: {{newText}}
$scope.add = function () {
$scope.items.push(
{
value: $scope.addVal,
text: $scope.addText
}
);
$scope.newVal = $scope.addVal;
$scope.newText = $scope.addText;
};
这会将新项推送到数组中,并将标签上的绑定设置为新值。你不需要看任何东西
这是一个例子