gpt4 book ai didi

angularjs - 如何使Angular保持两个字段同步?

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

我正在学习 Angular。作为练习,我将使用 jQuery 的现有应用程序转换为使用 Angular。

在我的页面上,我有两个输入。一个是组合框;另一个是文本输入。

当用户更改组合框中的选择时,文本输入将填充用户选择的文本,除非用户在组合框中选择名为“自定义”的条目。当用户选择“自定义”时,文本输入被清除并且焦点自动移动到文本输入以便用户键入自定义值。

每当用户手动将焦点移动到文本输入并键入某些内容时,组合框的值会自动更改为“自定义”。

在 Angular 中执行此操作的适当方法是什么?

我想如果我有两个相同的文本输入,我可以将它们 ng-bind 到同一个模型,但这是不同的。我猜我必须捕获事件并手动更新模型,但我想听听更有经验的人的意见。

最佳答案

您可以在 Controller 中的 $watch 中包装一些逻辑,或者可能更喜欢像 ng-clickng-change 这样的指令。

我认为 Nikos Paraskevopoulos 的回答很好,但它并没有真正回答您关于聚焦/清除输入的问题。

这是我可能完成此任务的一种方法。首先是 HTML 模板。

<input type="text"
ng-model="vm.selected.value"
ng-change="vm.inputChanged()"
focus-when-empty>

<select ng-model="vm.selected.option"
ng-change="vm.selectionChanged()"
ng-options="option for option in vm.options">
</select>

这很清楚。文本 inputselection 有单独的模型,有一些可供选择的选项和 ng-change 处理程序。 Controller 可能类似于
app.controller('MainController', function() {
var vm = this;

// your options to select from
vm.options = ['custom','one','two','three'];

// current text input value and dropdown selection
vm.selected = {
value: null,
option: null
};

// handle text input
vm.inputChanged = function() {
var index = vm.options.indexOf(vm.selected.value);
vm.selected.option = index > 0 ? vm.options[index] : vm.options[0];
};

// handle dropdown
vm.selectionChanged = function() {
var index = vm.options.indexOf(vm.selected.option);
vm.selected.value = index > 0 ? vm.selected.option : null;
};
});

Focusing on text input, when "custom"was selected, was little trickier so it's handled via simple focus-when-empty directive.
app.directive('focusWhenEmpty', function() {
return {
restrict: 'A',
scope: {
ngModel: '='
},
link: function(scope, element) {
// if there is no model, focus on element
scope.$watch('ngModel', function(value) {
if (!value) {
element[0].focus();
}
});
}
};
});

作为额外的奖励,如果您在选项中输入任何值,则选择会相应更新(因此它不再是“自定义”)。

这是相关的plunker,希望对您有所帮助! http://plnkr.co/edit/uJeV5L

imgur

关于angularjs - 如何使Angular保持两个字段同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30550069/

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