gpt4 book ai didi

javascript - 使用 ng-model 指令从动态创建的标签中提取数据

转载 作者:行者123 更新时间:2023-12-03 03:05:17 25 4
gpt4 key购买 nike

是否可以多次使用相同的 ng-model 指令并唯一地访问它们?

我有一个指令,用单个模板的多个实例填充页面。由于它是相同的模板,因此添加的所有 ng-model 属性都指向 Controller 中的同一变量。

我目前正在使用 document.getElementsByName() 所以我得到了一个可以迭代的列表,但是当尝试以这种方式获取数据时,与简单地引用变量中的变量相比,会更加困惑。 Controller 。

编辑:

此 HTML:

<div class="row">
<tib-copy></tib-copy>
</div>

获取注入(inject)并变成这样:

<tib-copy>
<fieldset class="col-md-2" style="margin-bottom: 10px">
<legend>Copy</legend>

<input type="text" ng-model="searchOptions.sourceServer">
<br/>
<input type="text" ng-model="searchOptions.sourcePath">
<br/>
<input type="text" ng-model="searchOptions.destServer">
<br/>
<input type="text" ng-model="searchOptions.destPath">
</fieldset>
</tib-copy>

再次执行此操作(单击调用函数以通过 ng-click 进行注入(inject)的按钮)将导致重复相同的 ng-model 标签在 DOM 中。

举个例子,我想获取“searchOptions.sourceServer”的所有 ng-model 属性作为列表或允许我单独提取值的东西。但由于双向绑定(bind),所有文本字段都更新为相同的值。

最佳答案

为此,您需要使用 ngModelController为您tibCopy指示。这意味着您在其中定义的每个模型都充当本地指令模型。然后,您必须将它们解析为更高级别的 ngModel您将该指令传递给其他组件。

例如,您可以从以下指令结构开始:

  App.directive('tbpCopy', 
function () {
return {
restrict: 'E',
require: 'ngModel',
templateUrl: '<fieldset class="col-md-2" style="margin-bottom: 10px">' +
'<legend>Copy</legend>' +
'<input type="text" ng-model="searchOptions.sourceServer">' +
'<input type="text" ng-model="searchOptions.sourcePath">' +
'<input type="text" ng-model="searchOptions.destServer">' +
'<input type="text" ng-model="searchOptions.destPath">' +
'</fieldset>',
link: function($scope, $element, $attrs, $model){
$model.$formatters.push(function(modelValue) {
if(modelValue){
return {
searchOptions: {
sourceServer: modelValue.searchOptions.sourceServer,
sourcePath: modelValue.searchOptions.sourcePath,
destServer: modelValue.searchOptions.destServer,
destPath: modelValue.searchOptions.destPath
}
};
}
});

$model.$render = function() {
if($model.$viewValue){
$scope.searchOptions = {
sourceServer: $model.$viewValue.searchOptions.sourceServer,
sourceServer: $model.$viewValue.searchOptions.sourcePath,
sourceServer: $model.$viewValue.searchOptions.destServer,
sourceServer: $model.$viewValue.searchOptions.destPath
}
}
};

$model.$parsers.push(function(viewValue) {
if(viewValue){
return {
searchOptions: {
sourceServer: viewValue.searchOptions.sourceServer,
sourcePath: viewValue.searchOptions.sourcePath,
destServer: viewValue.searchOptions.destServer,
destPath: viewValue.searchOptions.destPath
}
};
}
});
}
};
});

您将使用以下指令: <tbp-copy ng-model="ctrl.SomeHigherModel"></tbp-copy>

然后您将能够获取 ctrl.SomeHigherModel 内的基础值这应该等于:

searchOptions: {
sourceServer: 'some value',
sourcePath: 'some value',
destServer: 'some value',
destPath: 'some value'
}

关于javascript - 使用 ng-model 指令从动态创建的标签中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47191942/

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