Search code examples
jsonangularjsangular-nglist

angular js add JSON to ng-list


I have 3 properties included JSON object array 'notes'.

$scope.notes = [
        {
            'type':'txt',
            'name': 'JohnHenry',
            'text':'Greeting',
        }
    ]; 

My input field is

`<input type="text" placeholder="Text here..." ng-model="note.input" ng-list="," ng-enter="addnote()">`

I will type in below text into input textfield.

"txt-Glen-Negotiate Price, num-Phil-0939876, met-DrWalh-1505"

type property is to display icon. I wish to get as below JSON

$scope.notes = [
        {
            'type':'txt',
            'name': 'JohnHenry',
            'text':'Greeting',
        },{
            'type':'txt',
            'name': 'Glen',
            'text':'negotiate price',
        },{
            'type':'num',
            'name': 'Phil',
            'text':'0939876',
        },{
            'type':'met',
            'name': 'DrWalh',
            'text':'1505',
        }
    ];

How to convert input ng-list text to JSON objects.


Solution

  • Write your own directive

    app.directive('jsonConvert', function(){
      return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ngModel){
          scope.$watch(
            function(){
                return ngModel.$modelValue;
            }, function(newValue, oldValue){
                var value = ngModel.$modelValue
                if (value instanceof Array) return;
                var valueArr = value ? value.split(',') : value;
                if (!valueArr) return;
                for (var i = 0; i < valueArr.length; i++){
                  if (valueArr[i]){
                    var splitItem = valueArr[i].split("-");
                  }
                  valueArr[i] = {
                    type: splitItem[0] ? splitItem[0] : '',
                    name: splitItem[1] ? splitItem[1] : '',
                    text:  splitItem[2] ? splitItem[2] : ''
                  }
                }
                var result = valueArr;
                ngModel.$setViewValue(result);
            }, true);
        }
      }
    })
    

    Although the way you have defined what you want may not be scalable or best practise since it maps 0 to type, 1 to name and 2 to text

    Example - http://plnkr.co/edit/vtcpiYsTYKq3H2QTupyS?p=preview