ng-repeat内的按钮可以更新表单中的输入

时间:2013-07-26 21:27:25

标签: angularjs angularjs-ng-repeat angularjs-ng-click

我要做的是更新ng-repeat中的输入字段。我为每个用户点击ng-repeat内的按钮。单击按钮时,它应更新输入字段的值,该字段位于ng-repeat之外但在同一控制器中。我刚刚开始使用Angularjs,我似乎在这里缺少一些简单的东西,但是无法理解它。非常感谢任何帮助!

<div ng-app="MyApp">
    <div ng-controller="Main">
        <form name="myForm">
            <input type="email" ng-model="rootFolders">
            <button type="submit">Submit</button>
        </form> 
        <span ng-repeat="user in users" style="float:left">
            {{user.name}}<br>
            <button ng-click="rootFolders='{{user.login}}'">Load Email</button>
        </span>

    </div>
</div>

控制器

angular.module('MyApp', []);

function Main($scope) {
    $scope.rootFolders = 'bob@go.com';
    $scope.users = [
            {id:0,name:'user1',login:'user1@go.com',password:'123456'},
            {id:1,name:'user2',login:'user2@go.com',password:'123456'},
                    ]
}

这是小提琴:http://jsfiddle.net/DahDC/

2 个答案:

答案 0 :(得分:9)

您需要在范围内创建ng-click操作并将用户传递给当前行。

<div ng-app="MyApp">
    <div ng-controller="Main">
        <form name="myForm">
            <input type="email" ng-model="rootFolders">
            <button type="submit">Submit</button>
        </form> <span ng-repeat="user in users" style="float:left">
            {{user.name}}<br>
            <button ng-click="loadEmail(user);">Load Email</button>
        </span>
    </div>
</div>

angular.module('MyApp', []);

function Main($scope) {
    $scope.rootFolders = 'bob@go.com';
    $scope.users = [{
        id: 0,
        name: 'user1',
        login: 'user1@go.com',
        password: '123456'
    }, {
        id: 1,
        name: 'user2',
        login: 'user2@go.com',
        password: '123456'
    }, ]

    $scope.loadEmail = function (user) {
        $scope.rootFolders = user.login;
    }
}

试试吧。 FIDDLE

答案 1 :(得分:1)

我相信因为你在ng-repeat里面进行ng-click内部的赋值,所以在那里为本地范围分配rootFolders属性(由每个元素的ng-repeat实例化)。所以你实际上在ng-repeat的所有局部范围内分配了一个新属性。

edited your fiddle明确地表明了这一点。一个很好的学习点!

<div ng-app="MyApp">
<div ng-controller="Main">
    <form name="myForm">
        <input type="email" ng-model="rootFolders"> {{ rootFolders }}
        <button type="submit">Submit</button>
    </form> 
    <span ng-repeat="user in users" style="float:left">
        {{user.name}}<br>
        <button ng-click="rootFolders = user.login">Load Email {{ user.login }}</button><br/>
        {{ rootFolders }}
    </span>

</div>