trs
trs

Reputation: 863

Angular.js - How to pass the $index to a function?

This is my structure in scope:

$scope.tables = [
    {name: 'tweets',
    columns: ['message', 'user'],
    items: [
        {message: 'hello', user: 'mike'},
        {message: 'hi', user: 'bob'},
        {message: 'hola', user: 'bob'}
    ]
    },
    {name: 'users',
    columns: ['username'],
    items: [
        {username: 'mike'},
        {username: 'bob'}
    ]
    }
];

This is the "addTweet" function. Since the button that calls this function is generated from a loop, it needs to pass the $index to the function. I've tried the following but it doesn't work. The button doesn't seem to trigger anything at all. If I call the function from outside the loop though, it works.

$scope.addTweet = function(id){
    $scope.tables[id].items.push({message: $scope.message, user: $scope.user});
};

<table ng-repeat="table in tables">
    <form ng-submit="addTweet($index)">
        <tr>
            <td ng-repeat="column in table.columns">
                <input type="text" ng-model="column"></input>
            </td>
            <td>
                <button type="submit">Add Row</button>
            </td>
        </tr>
    </form>
</table>

Upvotes: 0

Views: 2988

Answers (1)

IvanMalenko
IvanMalenko

Reputation: 427

Don't use tag 'form' inside tag 'table' - it's incorrect html syntax.

Use this way:

<table ng-repeat="(tableIdx, table) in tables">
    <tr>
        <td ng-repeat="column in table.columns">
            <input type="text" ng-model="column"></input>
        </td>
        <td>
            <button type="submit" ng-click="addTweet(tableIdx)">Add Row</button>
        </td>
    </tr>
</table>

or this

<form ng-submit="addTweet($index)" ng-repeat="table in tables">
    <table>
        <tr>
            <td ng-repeat="column in table.columns">
                <input type="text" ng-model="column"></input>
            </td>
            <td>
                <button type="submit">Add Row</button>
            </td>
        </tr>
    </table>
</form>

I'm sorry. I didn't see addTweet function code. $scope.message and $scope.user properties are not initialized in your $scope, because this binding ng-model="column" refer to the $scope.table[tableId].columns[columnId]

If you want to add new item and work with dynamic model names try this:

<tr ng-init="table.newPost={}">
    <td ng-repeat="column in table.columns">
        <input type="text" ng-model="table.newPost[column]"></input>
    </td>
    <td>
         <button type="submit">Add Row</button>
    </td>
</tr>

And code for addTweet function:

$scope.addTweet = function(id) {
    $scope.tables[id].items.push($scope.tables[id].newPost);
    $scope.tables[id].newPost = {};
}

Upvotes: 2

Related Questions