PortalGuy PortalGuy - 1 year ago 86
AngularJS Question

Dynamically assign ng-bind in form

I have JSON like with data like this, unfortunately I cannot fix the data which comes from third party

$scope.mydata = {
"SOB0": "7",
"SOB1": "70",
"SOB2": "790",
"wb0": "7",
"wb1": "17",
"wb2": "8",

The problem is the data received in JSON is not always the same for, the number of attributes, which may be one or more for each type i.e one attr SOB0 or many SOB0, SOB1, SOB2..

In the form I want to bind this data to a input field based on the number of attributes in the JSON for example if I have only three of type "SOB"

{"SOB0": "7", "SOB1": "70","SOB2": "790"..}

input ng-model="mydata.SOB0" size=6
input ng-model="mydata.SOB1" size=6
input ng-model="mydata.SOB2" size=6

There seems no way to interpolate like

or call a function to dynamically bind on the fly based on JSON.

Any help would be appreciated.

Answer Source

i would put all my value of inputs in a $scope dict like this

//inside angular controller
$scope.values = {};

in the html:

<div ng-repeat="i in Object.Keys(mydata)"> 
    <input ng-model="values[i]">

Object.keys(object) will return an array with all the keys of a given object, in this case, the variable 'i' will be your SOB keys so then all the inputs will be binded to a dynamic dict which will use their key to reference the value inputed

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download