0

I am trying to access the object dynamically based on the ng-click.I will have lot's of form with button like this.

HTML

<button type="button" id="news" ng-click="home.addnew()">Update</button>
<button type="button" id="allocation" ng-click="home.addnew()">Update</button>
<button type="button" id="create" ng-click="home.addnew()">Update</button>

My Object

"home": {
    "news": [{
        "type": "cd",
        "title": "title1",
    }],
    "allocation": [{
        "type": "cd",
        "title": "title2",
    }],
        "create": [{
        "type": "cd",
        "title": "title3",
    }]
    .......etc
}

Angularjs Controller

$scope.home.addnew = function(){
    var type = $(event.target).attr("id");
       $scope.home.news.title; // Here how can I access that "news","allocation","create" Dynamically
       $scope.home.type.title // I have tried like this 
}

I am getting error

Cannot read property 'title ' of undefined
1
  • Is $scope.home assigned the above json object? Commented Aug 23, 2016 at 14:04

3 Answers 3

4

Your trying to access object property instead of array.

It should look like this

$scope.home.addnew = function(){
    var type = $(event.target).attr("id");
    $scope.home[type][0].title; 
}
Sign up to request clarification or add additional context in comments.

Comments

0

You may use brackets for array

 var dynamicType ='news'; 
                var obj ={"home": {
                "news": [{
                "type": "cd",
                "title": "title1",
                }],
                "allocation": [{
                "type": "cd",
                "title": "title2",
                }],
                "create": [{
                "type": "cd",
                "title": "title3",
                }]
            }};
    console.log(obj.home[dynamicType][0].title); 

Comments

0

Are you sure that you have attached home to $scope as one of the user already commented. $scope.home needs to exist before you start working on it.

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.