angularjs - How to make Angular keep two fields in sync? -
i'm learning angular. exercise, converting existing application uses jquery use angular.
on page, have 2 inputs. 1 combobox; other text input.
when user changes selection in combobox, text input populated text of user's selection, unless user selects entry called "custom" in combobox. when user selects "custom", text input cleared , focus automatically moves text input user key in custom value.
whenever user manually moves focus text input , keys in something, value of combobox automatically changes "custom".
what appropriate way go doing in angular?
i suppose if had 2 identical text inputs, ng-bind them same model, different. i'm guessing must capture events , manually update model, i'd hear more experienced folks.
you wrap logic inside $watch in controller or maybe prefer directives ng-click , ng-change.
i think nikos paraskevopoulos' answer 1 didn't answer question focusing/clearing inputs.
here's 1 way might accomplish this. first html template.
<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 option in vm.options"> </select> that's pretty clear. there's separate model text input , selection, options choose , ng-change handler both. controller like
app.controller('maincontroller', function() { var vm = this; // options select vm.options = ['custom','one','two','three']; // current text input value , 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" selected, little trickier it's handled via simple focus-when-empty directive.
app.directive('focuswhenempty', function() { return { restrict: 'a', scope: { ngmodel: '=' }, link: function(scope, element) { // if there no model, focus on element scope.$watch('ngmodel', function(value) { if (!value) { element[0].focus(); } }); } }; }); and added bonus, if type in of values in options, selection updated accordingly (so it's not "custom" anymore).
here's related plunker, hope helps! http://plnkr.co/edit/ujev5l
Comments
Post a Comment