Angular.js - 如何将$ index传递给函数?

时间:2015-04-06 22:01:26

标签: arrays angularjs angularjs-directive angularjs-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'}
    ]
    }
];

这是" addTweet"功能。由于调用此函数的按钮是从循环生成的,因此需要将$ index传递给函数。我尝试了以下但是它没有用。按钮似乎根本没有触发任何东西。如果我从循环外部调用函数,它可以工作。

$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>

1 个答案:

答案 0 :(得分:2)

不要在标签'table'中使用标签'form' - 这是不正确的html语法。

使用这种方式:

<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>

或者

<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>

对不起我没有看到addTweet功能代码。您的$scope.message未初始化$scope.user$scope属性,因为此绑定ng-model="column"引用了$scope.table[tableId].columns[columnId]

如果您想添加新项目并使用动态模型名称,请尝试:

<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>

addTweet函数的代码:

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