0

I am able to get both attribute name and value from user input

{{attribute}} and {{value}}

how do i add these to an existing json object

$scope.items ={
 name: peter,
 age: 16,
 {{attribute}}: {{value}}
}
3
  • is attribute also a user input? If yes then you can trigger a function using ng-change of the input field and set the attribute and value to the object. And if you already know the attribute use ng-model. Commented Sep 12, 2016 at 4:19
  • you could use $scope.items[$scope.attribute] = $scope.value but why you would want to do this I don't understand. Commented Sep 12, 2016 at 4:19
  • i am trying to create a user interface where user can create custom form, means they name their input field labels Commented Sep 12, 2016 at 8:10

2 Answers 2

2

You could use bracket notation.

$scope.items[$scope.attribute] = $scope.value;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! didnt know i can do that, great lesson
0

Here's the plunker for your problem statement,using ng-change I've called a function to create the JSON object dynamically when ever user changes anything in the input fields or form. Below is the look of the controller where we create the JSON object

var myApp = angular.module('Test', []);
myApp.controller('MainCtrl', ['$scope', function($scope) {

  $scope.input={};
  $scope.items={};
  $scope.createObj = function(){
    $scope.items['name'] = $scope.input.name;
     $scope.items['age'] = $scope.input.age;
  };

}]);

HTML will look like this:

<body ng-app="Test" ng-controller="MainCtrl">
    <h5>Name:</h5>
    <input type="text" ng-model="input.name" ng-change="createObj()"/>
    <h5>Age :</h5>
    <input type="text" ng-model="input.age" ng-change="createObj()"/>
    <pre>{{items}}</pre>
  </body>

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.