gpt4 book ai didi

javascript - ng-model 绑定(bind)到 ng-repeat Angularjs 中的元素

转载 作者:行者123 更新时间:2023-11-30 10:01:04 24 4
gpt4 key购买 nike

如何将 ng-model 绑定(bind)到 ng-repeat 中的元素?事实上,我想将数组中的对象绑定(bind)到元素,并在输入元素中键入时使用新的 ng-model 创建新的输入元素。而在此示例中,所有 ng-model 都是相同的。

var myApp = angular.module('app', []);
myApp.controller("MyCtrl",function($scope){
$scope.items = [];
$scope.item = {
phone:""
};
$scope.items.push($scope.item);

$scope.addItem = function(index){
if($scope.items[index+1] == null)
$scope.items.push($scope.item);
console.log($scope.items);
}

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<div ng-repeat="line in items track by $index">
<!-- typing here should auto update it's preview above -->
<input ng-model="line.phone" ng-keydown="addItem($index)"/>
<!-- many other fields here that will also affect the preview -->
</div>
</div>

最佳答案

我想你想要这个。注意我用

$scope.items.push(angular.copy($scope.item))

制作对象的副本。如果没有这个,您总是会引用数组中的相同对象,因此更改其中一个对象也会导致其他对象也发生更改。

var myApp = angular.module('app', []);
myApp.controller("MyCtrl",function($scope){
$scope.items = [];
$scope.item = {
phone:""
};
$scope.items.push(angular.copy($scope.item));

$scope.addItem = function(index){
if($scope.items[index+1] == null)
$scope.items.push(angular.copy($scope.item));
console.log($scope.items);
}

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<div ng-repeat="line in items track by $index">
<!-- typing here should auto update it's preview above -->
<input ng-model="line.phone" ng-keydown="addItem($index)"/>
<!-- many other fields here that will also affect the preview -->
</div>
</div>

关于javascript - ng-model 绑定(bind)到 ng-repeat Angularjs 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31669432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com