2

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?

3 Answers 3

6

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    
};
Sign up to request clarification or add additional context in comments.

1 Comment

This solution worked for me while the accepted solution did not.
3

Try this:

HTML:

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

JavaScript:

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

3 Comments

Yep, or submit(i) if you want to pass the whole item (not just the id).
I'm very confused by this answer, what is addBrandModelFilter? Why is it not $scope.submit = function(useId) {};?
@Thomas you're right. I've corrected this. The error came from the fact that I wrote it quickly and copied the source code from my project.
2

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/

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.