我创建了一个指令,只要单击“添加”按钮就可以添加一些内容。但我不知道如何在这些新输入中获得所有值。
HTML代码
angular.module('myApp', [])
.controller('myController', function() {
})
.directive('addContent', function($document, $compile) {
return {
restrict: 'A',
replace: false,
link: function(scope, element, attr) {
element.on('click', function() {
var newcontent = '<input type="text" ng-model="myModel"><br>';
angular.element($document[0].querySelector('.newcontent')).append($compile(newcontent)(scope));
})
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="newcontent" ng-app="myApp" ng-controller="myController">
<button type="button" add-content>Add</button><br><br>
</div>
那么,如何为每个创建的新输入设置不同的ng-model
值,如何在控制器中获取此值?
你可以用这样的东西:
在指令中
var count = 0;
var model = scope.$eval(attr['addContent']);
获取html中指定的基本名称newcontent
变量以使用该基本名称和增量计数器,如下所示:var newcontent = '<input type="text" ng-model="' + model + (count++) + '"><br>';
控制器
$scope.buttonModel = 'buttonModelReference';
$scope[$scope.buttonModel + $scope.index]
其中$scope.index
是输入的索引(其中0
是创建的第一个输入)风景
add-content="buttonModel"
这样的修改后的指令,其中buttonModel
是控制器中定义的变量。加代码(仅用于演示目的)
showModel
函数显示一个(动态创建的)输入的值,作为参考传递输入的索引(0
零是创建的第一个输入的索引)angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.index;
$scope.buttonModel = 'buttonModelReference';
$scope.showModel = function() {
console.log($scope[$scope.buttonModel + $scope.index]);
}
})
.directive('addContent', function($document, $compile) {
var count = 0;
return {
restrict: 'A',
replace: false,
link: function(scope, element, attr) {
element.on('click', function() {
var model = scope.$eval(attr['addContent']);
var newcontent = '<input type="text" ng-model="' + model + (count++) + '"><br>';
angular.element($document[0].querySelector('.newcontent')).append($compile(newcontent)(scope));
})
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="newcontent" ng-app="myApp" ng-controller="myController">
<button type="button" ng-click="showModel()">showModel</button> <input ng-model="index" type="number" placeholder="select the model index starting from 0" /> <br><br>
<button type="button" add-content="buttonModel">Add</button><br><br>
</div>