所选项目不会显示

时间:2013-08-16 02:19:38

标签: angularjs angularjs-ng-click

我想要做的就是在主列表项目下方显示所选项目。我以前做过这个,但由于某种原因,它只是没有表现,我无法弄清楚我错过了什么。

html(修剪为相关部分):

<ul>
    <li data-ng-repeat="user in users" ng-click="$parent.selectUser($index)" ng-model="$index">
        {{user.userName}}
    </li>
</ul>

<p>Selected: {{selected.userName}}, #<b>{{$index}}</b></p>

js:

(function (app) {
    app.controller('UsersController', [ '$scope', function ($scope) {
        $scope.selectUser = function ($index) {
            $scope.selected = $index;
            console.info('selected1=' + $index);
        };
        $scope.selected = null;
    }]);
});

控制台日志显示选择的索引,但在html的最后一行没有任何反应 - 没有selected.userName,没有$ index。我尝试了各种各样的变化,没有任何反应。我错过了什么?提前谢谢!

(注意:我也不确定我是否正确使用了ng-model,但这似乎是我是否可以让所选的$ index显示出来的偶然事件。)

1 个答案:

答案 0 :(得分:1)

您正试图在$index之外使用ng-repeat这不起作用,因为$index仅在ng-repeat上下文中可用。

因为你正在设置

$ scope.selected = $ index;

您需要使用selected变量

我认为您想要的是在点击时选择用户。这应该是这样做的。

<ul>
    <li data-ng-repeat="user in users" ng-click="selectUser(user,$index)" ng-model="$index">
        {{user.userName}}
    </li>
</ul>

<p>Selected: {{selected.userName}}, #<b>{{index}}</b></p>

您的控制器将

$scope.selectUser = function (user,index) {
            $scope.selected = user;
            $scope.index=index;
        };