Question

I have a collection of items in $scope.data with fields "id","name" & "age", that are being displayed in the view using ng-repeat directive. For each set of items, there is a corresponding "edit button".

I want to be able to access values for the particular set of items for which edit button was pressed.

Html:

<div ng-controller="Ctrl">
    <div ng-repeat="i in data">
        Name: {{i.name}}
        Age: {{i.age}}

        <form ng-submit="submit()">
            <input type="text" ng-model="i.id"/>
            <input type="submit" value="Edit" />
        </form>
    </div>
</div>

Script:

function Ctrl($scope) 
{
  $scope.data = [
    {id:1,name:"Alex",age:22},
    {id:2,name:"Sam", age:28}
    ];

    $scope.submit = function() {
        //access id of user for which edit was clicked
    };
}

What is the right way to do this?

Was it helpful?

Solution 2

Try this:

HTML:

<form ng-submit="submit(i.id)">

JavaScript:

$scope.submit = function(userId) {
  // you have userId
};

OTHER TIPS

Instead of a form, I would suggest you just use a button:

<div ng-controller="Ctrl">
    <div ng-repeat="i in data">
        Name: {{i.name}}
        Age: {{i.age}}

        <input type="text" ng-model="i.id"/>
        <button ng-click="submit(i)">Edit</button>

    </div>
</div>

Just send i into the button click event (I suppose you could use form if you need validation, but your example doesn't seem to need it).

Your submit function then changes to:

$scope.submit = function(selectedItem) {

    // here you now have access to selected item    
};

One option is to just use an ng-click within a button that calls your submit passing in i

<div ng-controller="Ctrl">
    <div ng-repeat="i in data">
        Name: {{i.name}}
        Age: {{i.age}}

        <button ng-click="submit(i);">edit</button>

    </div>
</div>

and the function:

$scope.submit = function(i) {
    console.log(i);
    //access id of user for which edit was clicked
};

Here's a fiddle of that working: http://jsfiddle.net/pRAcP/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top