Search code examples
javascriptangularjsangularjs-ng-repeatangular-ngmodelangularjs-material

AngularJS - Get current object from ng-repeat


I'm working on a user profile "card" type of thing for our application. The idea is to leverage the AngularJS Material library to create a simple interface for non admin users to manage other users assigned to them.

I have an ng-repeat running to pull the data for these cards, and then generate the markup for them, like so:

<!-- language: lang-js -->
<div class="col-md-6 md-padding float-left" ng-repeat="user in allUsers">
    <md-toolbar class="row col-md-12 md-hue-5 md-dense px-0">
        <div class="md-toolbar-tools">
            <span class="col-md-10">{{ user.name }}</span>
            <md-button id="managedUserDetails" type="submit" ng-click="null" class="md-fab" aria-label="Click to view profile">
                <md-icon md-svg-src="/images/svg/action/ic_open_in_new_48px.svg"></md-icon> 
            </md-button>
        </div>
    </md-toolbar>

    <div class="row col-md-12 border border-dark">
        <div class="row col-md-12">
            <md-input-container class="md-block col-md-6" flex-gt-xs>
                    <label>Name:</label>
                    <input ng-model="user.name" class="detailDisabled" disabled>
            </md-input-container>

//code continues for other bits, and yes, the tags are closed :)

My question is regarding the md-button element. In it, I would like to use a function to bring up an expanded view of that user, but to do this I need the data from the particular user card that the button lives in. Then I can use that data to populate the expanded view.

So, the question:

Is there a way to tell Angular "Give me the data that you used to generate the parent element?"

If not, i'll have to do some thinking, as all I can think of right now are.......non-elegant solutions :)


Solution

  • You can pass the user object directly to the ng-click, using ng-init will call that method all the time when the element generates,

    <md-button id="managedUserDetails" ng-click="getAdvancedView(user)" class="md-fab" aria-label="Click to view profile">
       <md-icon md-svg-src="/images/svg/action/ic_open_in_new_48px.svg"></md-icon> 
    </md-button>
    

    And on your controller you can access the whole user object on the button click event,

    $scope.getAdvancedView = function(user) {
       console.log(user.name);
    }