trainoasis
trainoasis

Reputation: 6720

Pass a variable to controller function ?

I want to show some item specific data when an item is clicked. This is what I have so far:

<div ng-repeat="item in items">
     <p ng-click="toggleDetails()">{{item.name}}</p>
</div>  

<div ng-show="showDetails">
    <p>PERSON ID</p>
    <p>PERSON NAME</p>
    <p>other person information … </p>
</div>  

What is important for me, is that the data that I show must be in a different DIV then items are listed. Otherwise, show/hide works ok!

I use this method in my controller to show my 'details' div:

$scope.toggleDetails = function(){
    $scope.showDetails = !$scope.showDetails;
};

My items are for now defined statically in controller like this:

$scope.items = [
    {
        id: 0,
        name: 'ITEM1'
    },
    {
        id: 1,
        name: 'ITEM2'
    },
    {
        id: 2,
        name: 'ITEM3'
    }
];

How can I do this? I tried to pass a variable to toggleDetails method, like toggleDetails({{item.id}}) but that did not seem to work? Do I need to define a service for this? I want to keep it as simple as possible, since it's gonna get too big to maintain anyway…

Thanks for any help - if I was unclear please ask for more info

Upvotes: 0

Views: 64

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67326

You just need to add the concept of a selected item and send that one in when you toggle:

<div ng-repeat="item in items">
     <p ng-click="toggleDetails(item)">{{item.name}}</p>
</div>  

<div ng-show="showDetails">
    <p>{{ selectedItem.id }}</p>
    <p>{{ selectedItem.name }}</p>
    <p>other person information … </p>
</div> 

JS:

$scope.selectedItem = null;
$scope.toggleDetails = function(item){
    $scope.selectedItem = item;
    $scope.showDetails = !$scope.showDetails;
};

Upvotes: 1

Related Questions