1

Simple question, but struggling to find an answer.

HTML

<div class="col-sm-5">
<input type="text" class="form-control" placeholder="key" 
ng-model="main.key" ng-change="updateJson()">
</div>
<div class="col-sm-7">
<input type="text" class="form-control"  placeholder="value" 
ng-model="main.value" >

JS

$scope.updateJson=function(){
  this.jsonObject +=this.key+":"+this.value;
};

I have a text field which is bound to UpdateJson, it outputs this as I type in the text boxes.

undefinedundefined:undefinedundefined:undefinedundefined:undefined

How do I concatenate a String in a way that it recognizes the type correctly?

6
  • What exactly are you outputting, and what are you expecting to see? Commented Dec 15, 2016 at 16:35
  • I don't see context or definition for this.jsonObject. Please elaborate what you're seeing on screen. Best is provide a plunkr. Commented Dec 15, 2016 at 16:39
  • 1
    The value of key would be on $scope.main.key, because of this in the template ng-model="main.key". But basically there are a number of different reasons it could be outputting undefined, but as @Dalorzo said, we don't normally use this in angular. Commented Dec 15, 2016 at 16:40
  • thanks all, updated to elaboarte I hope. I read this. should be used with the new controller As moodel Commented Dec 15, 2016 at 16:43
  • 1
    I think you want to do this , please let me kbow if i am not getting you $scope.updateJson=function(){ $scope.jsonObject[$scope.main.key]=$scope.main.value; }; Commented Dec 15, 2016 at 17:01

1 Answer 1

1

Assuming $log is injected in controller, and you use $scope as it occurs in your view, try

var jsonObject = "...";
$scope.updateJson=function(){
   var keyValue =  $scope.key+":"+$scope.value;
   $log.debug("keyValue is "+keyValue);
   jsonObject += keyValue;
};

You should see the key and value entered in your input fields concatenated with a colon in the console. And the controller variable jsonObject should have the key and value appended.

Note: If your goal is to serialize some input form fields through json, you should an object, e.g.

var theObject = { 
   key: 'some key',
   value: 'some value'
}

And serialize it with JSON.stringify(theObject).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.