0

All I want to do is show the selected item below the master list o' items. I've done this before, but for some reason it's just not behaving and I can't figure out what I'm missing.

the html (trimmed down to just the relevant part):

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

the js:

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

The console log shows up with the index of the selection, but nothing happens in the last line of the html -- no selected.userName, no $index. I've tried all kinds of variations and nothing happens. What am I missing? Thanks in advance!

(note: I'm not sure I'm using ng-model there correctly, either, but that seems to be incidental to whether or not I can get the selected $index to show up.)

4

1 回答 1

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;
        };
于 2013-08-16T02:58:18.083 回答