Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-model combobox with other option and a textbox

I have a combobox with ng-model='languale'. I also have a predefined list let say 'English', 'French', 'German' and 'Other'

If I select Other option then another textbox need to be appeared. I have achived this functionality with ng-show.

Now my problem is in my JSON structure there is only one filed for language as follows

var peopleData = {
           language : 'English'
}

So I am not able to give same name as ng-model='peopleData.language' in both select and textbox.

Since my backend developers do not want add an extra property in JSON. So I have to handle it in different way. I do not want to write any logic at the time of sending data to Service (create or manupulate JSON structure).

So is there any way to solve this problem?

Note: I know I can use $scope.$watch but still I am looking for better solution, such as completely handled from view it self, otherwise it could be a performance issue.

like image 362
Partha Sarathi Ghosh Avatar asked May 31 '16 10:05

Partha Sarathi Ghosh


1 Answers

.:: Answer Upadated ::.


How about writing a simple directive?

HTML:

<select ng-model="ctrl.main" f-model="peopleData.language" ng-options="i as i for i in langs"></select>
<input type="text" ng-model="ctrl.extra" f-model="peopleData.language" ng-if="ctrl.main == 'Other'">

JS:

app.directive('fModel', [function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      scope: {
        fModel: '='
      },
      link: function(scope, element, attrs, ngModel) {

        var handler = function(val) {
          var newVal = angular.copy(val || scope.fModel || '');
          scope.$applyAsync(function() {
            scope.fModel = newVal;
          });
          return newVal;
        }

        ngModel.$parsers.push(handler);
        ngModel.$formatters.push(handler);
      },
    };
}]);

Check it out live IN THIS PLUNKR:

like image 144
MeTe-30 Avatar answered Nov 15 '22 05:11

MeTe-30