如果所有其他元素都填写在AngularJS中,如何动态添加新的输入元素
How dynamically add new input element if all others was filled in AngularJS
请观看此Plunker
因此,我使用angular,当所有其他输入都被填充时,需要添加新的输入字段(默认情况下,在页面上放置5个输入,如果所有输入都被填满,如果新输入也使用,则会自动添加一个输入,等等)。
对于生成输入,我使用ng repeat和name_list[]:
<div collect-input>
<div class="form-group" ng-repeat="(i, name) in name_list track by $index">
<div class="row">
<div class="col-xs-12">
<input class="form-control" type="text" ng-model="data.name_list[i]" add-input/>
</div>
</div>
</div>
每个输入都有指令attr"add input",其中包含$watch()方法。此方法跟踪$isEmpty参数何时更改。然后value函数将此参数的值传递给listen函数。
directive('addInput', ['$compile', '$sce', '$timeout', function ($compile, $sce, $timeout) {
return {
restrict: 'A',
require: ['^collectInput', '?ngModel'],
link: function (scope, element, attrs, ctrl) {
var collectInput = ctrl[0];
var ngModel = ctrl[1];
$timeout(function(){
scope.$watch(
function(){
return ngModel.$isEmpty(ngModel.$modelValue);
},
function(isEmpty){
collectInput.reportInput(ngModel, isEmpty);
}
);
},1000)
}
}
}]);
然后,此函数调用放置在父指令"collect input"中的"reportInput()"。该函数的主要目标是将新的输入名称添加到name_list[]中,以便通过ng重复生成
userApp.directive('collectInput', function() {
return {
restrict: 'A',
controller: function($scope) {
var dirtyCount = 0;
this.reportInput = function(modelValue, isEmpty) {
var count = $scope.name_list.length;
if (isEmpty == false){
dirtyCount ++;
console.log('+1:' + dirtyCount);
}
if (isEmpty == true){
if (dirtyCount <= 0){
dirtyCount = 0;
console.log('0:' + dirtyCount);
}
else if(dirtyCount > 0){
dirtyCount --;
console.log('-1:' + dirtyCount)
}
}
if (count === dirtyCount) {
$scope.name_list.push(modelValue);
//dirtyCount = dirtyCount + 1;
}
console.log('count:' + count);
console.log('dirtyCount:' + dirtyCount);
console.log(modelValue)
}
},
link: function(scope, element, attrs) {
}}});
因此,当我填充了5个默认输入时,在它出现新输入后一切都很好,但它都在我的IDE中,如果我只为5+标签添加一个符号(在plunker中,由于某种原因,它不起作用),它会完美地工作,但当我添加或删除更多代码逻辑崩溃时。这很难解释。我希望Plunker代码能更多地澄清这一点。
没有经过测试,可以进行优化,但我的想法是:
HTML:
<div class="form-group" ng-repeat="name in name_list">
<div class="row">
<div class="col-xs-12">
<input class="form-control" ng-model="name"/>
</div>
</div>
</div>
JS:
//watch any modification in the list of names
$scope.$watchCollection('data.name_list', function (list) {
//is there an empty name in the list?
if (!list.filter(function (name) { return !name; }).length) {
//if not, let's add one.
data.name_list.push('');
//and that will automatically add an input to the html
}
});
我看不出指令有什么意义。
相关文章:
- 将列表元素动态添加到ul元素中
- 将输入 html 元素动态关联到颜色选取器
- 媒体元素 - 动态加载音频
- 根据其内部元素动态更改 CSS
- 编写脚本以向元素动态添加.current(类似活动类)的场景
- 使用knockoutjs虚拟元素动态创建html部分
- 将JS中的元素动态添加到XUL中
- 如何从jquery中获得元素动态附加的完整表
- 使用jquery向li元素动态添加类
- 点击事件不't在尝试将元素动态添加到<ul>标签
- 使用Knockout.js Issue将元素动态添加到嵌套列表中
- 如何从DOM元素动态禁用popover
- 将样式元素动态插入DOM的最后一种跨浏览器方式
- 无法将元素动态添加到数组中
- 指令如何等待元素'动态插值属性被处理?
- 设置活动元素和非活动元素(动态)
- 是否可以使用JS/PHP为网页中的元素动态分配ID
- 如何制造<光>元素动态调整以填充浏览器窗口的整个宽度
- 基于页面元素动态构建菜单结构
- 向现有元素动态添加删除绑定