simi kaur
simi kaur

Reputation: 1277

adding an array property to object in angular js

I have an object called user:

It has properties like user.name, user.age e.tc.

Now, I need to add an array to user object called subjects via ng-model.

This is what i did inside of ng-repeat:

    <input type="text" ng-model="user.subjectname[$index]" 
  name="subject" ng-required="true" placeholder="Enter a subject name">

and when I do console.log(user.subjectname), it looks like this:

enter image description here

Now, after this, I wanted to do something like this:

<div ng-repeat="data in user.sujects">
                  <td>{{data}} </td>
                   </div>

But it does not work.

Try2:

In my my service that is called from controller, I tried this,

        if(dataArray== null)
                var dataArray=[];

            console.log("scop.user.subjectname...................." + user.subjectname);
            for(var i in user.subjectname)
            {   dataArray.push(user.subjectname[i]) 
            }
            user.data=dataArray;

so, now if I do,

 <div ng-repeat="data in user.data">
                      <td>{{data}} </td>
                       </div>

I still get nothing.

Can I get some direction to deal with this?

Upvotes: 1

Views: 372

Answers (1)

user1364910
user1364910

Reputation:

Like I told you in your previous question, and showcased in a jsbin.

You need to use the (key, val) in object syntax to get those values out of user.subjectname

ng-repeat="(key, val) in user.subjectname" ng-bind="val"

If you need to transform this object into an array:

$scope.arr = [];

Object.keys(user.subjectname).forEach(function (key) {
  arr.push(user.subjectname[key]);
});

Then if you need to output that

ng-repeat="a in arr" ng-bind="a"

edit: after further explanation from you, I'm assuming this jsBin highlights something close to what you are after.

Upvotes: 2

Related Questions