我想从显示的单个源中单独更改动态添加的类似 ng-repeat 值,您可以从我下面的代码中看到,如果我们单击动态附加的 div,它将在右侧显示一个表单,如果我们可以添加输入文本字段,但我的问题是,当我尝试添加或更改它绑定(bind)并添加到所有 div 的文本时,我只想将输入字段添加到选定的 div。
请不要使用 ng-repeat 方法来推送“再次添加”按钮的值,仅需要从追加方法添加..
var app = angular.module('myapp', ['ngSanitize']);
app.controller('AddCtrl', function ($scope, $compile) {
$scope.items = [];
$scope.add_New = function (index) {
var itemhtml = '<div ng-click="select()" class="content">//click here// <div ng-repeat="item in items">{{$index + 1}}. {{item.name}}</div></div>';
var item = $compile(itemhtml)($scope);
angular.element(document.getElementById('drop')).append(item);
};
$scope.add = function () {
$scope.items.push({
name: "hi"
});
};
$scope.select = function(){
$scope.showItem = true;
}
});
.add{
position: absolute; height: auto; width: 200px; left: 0; right: auto; top: 0; bottom: 0;
}
.show{
position: absolute; width: auto; left: 200px; right: 0; top: 0; bottom: 0;
border:1px solid red;
float:right;
}
.content{
border:1px solid blue;
}
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<link href="style.css" rel="stylesheet" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.0-rc.0/angular-sanitize.min.js"></script>
</head>
<body ng-controller="AddCtrl">
<div class="add"><button ng-click="add_New($index)">add Again</button>
<div id="drop">
</div>
</div>
<div ng-show="showItem" class="show">
<div ng-repeat="item in items">
{{$index + 1}}.<input type="text" ng-model="item.name">
</div>
<button ng-click="add()">Add</button>
</div>
</body>
</html>
最佳答案
这是因为您对所有主项目和子项目使用相同的列表。 因为您不想使用 ngrepeat,所以您必须为所有主要项目创建索引。
创建一个 main 列表。每次创建主项目时,都会增加索引。
之后,每个主项目都有一个值列表(子项目)。
希望如您所料!
这里的工作代码:
app.controller('AddCtrl', function ($scope, $compile) {
$scope.items = [];
$scope.index = 0;
$scope.currentIndex = -1;
$scope.add_New = function (index) {
var itemhtml = '<div ng-click="select(' + $scope.index + ')" class="content">//click here first// <div ng-repeat="item in items[' + $scope.index + '].values">{{$index + 1}}. {{item.name}}</div></div>';
var item = $compile(itemhtml)($scope);
angular.element(document.getElementById('drop')).append(item);
$scope.items[$scope.index] = {};
$scope.index++;
};
$scope.add = function () {
if ($scope.items[$scope.currentIndex].values == undefined)
$scope.items[$scope.currentIndex].values = [];
$scope.items[$scope.currentIndex].values.push({
name: "hi"
});
};
$scope.select = function(index){
$scope.showItem = true;
$scope.currentIndex = index;
}
});
<body ng-controller="AddCtrl">
<div class="add"><button ng-click="add_New()">add Again</button>
<div id="drop">
</div>
</div>
<div ng-show="showItem" class="show">
<div ng-repeat="item in items[currentIndex].values">
{{$index + 1}}.<input type="text" ng-model="item.name">
</div>
<button ng-click="add()">Add</button>
</div>
</body>
关于javascript - 更改从单一来源动态添加的类似 ng-repeat 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34875273/