如何通过索引访问数组中的数据以获取AngularJs中的重复项

时间:2018-08-29 18:53:11

标签: angularjs

我是AngularJs的新手。我有一个显示 ng重复学生姓名的主视图。当您单击每个名称时,它必须显示该学生的详细信息。

但是,当我单击每个名称时,视图不会显示该特定学生的详细信息。

这是我的主视图:

<a ng-href="#!/info/{{$index}}">        
    <div class="info" ng-repeat="user in users | orderBy: order | filter:expression">
        <div class="img">
            <img ng-src="{{user.image}}">
        </div>
        <div class="text">
            <h3 style="color: #007acc;"> Student Details For:</h3>
            <h2>{{user.name}}</h2>
        </div>
    </div>
</a>

这是我的信息视图:

<div class="text" style="padding: 0 5%;">
    <p><span>Name:</span> &nbsp; &nbsp;{{info.name}}</p>
    <p><span>Room:</span> &nbsp; &nbsp;{{info.room}}</p>
    <p><span>Cell:</span> &nbsp; &nbsp;{{info.cell}}</p>
    <p><span>Guardian Cell:</span> &nbsp; &nbsp;{{info.nokcell}}</p>
    <p><span>Guardian Email:</span> &nbsp; &nbsp;{{info.nokemail}}</p>
    <br>
</div> 

这是我的js:

    var app = angular.module("myApp", ['ngRoute']);
app.config(function($routeProvider){
    $routeProvider
    .when("/", {
        controller: "mainController",
        templateUrl: "views/home.html"
    })
    .when("/info/:id", {
        controller: "infoController",
        templateUrl: "views/info.html"
    })
    .otherwise({
        redirectTo: "/"
    })
});
var data = [
{
    name: "   Andrea Toe",
    room: 12,
    cell: "0724884888",
    nokcell: "0724884975",
    nokemail: " ",
    image: "images/female.jpg"
},
{
    name: "Relebogile Maile",
    room: 3,          
    cell: "07248844322",
    nokcell: "24 Old Pretoria Rd, Midrand",
    nokemail: " ",
    image: "images/female.jpg"
},
{
    name: "Siyabonga Ntshangase",
    room: 1,
    cell: "0753284888",
    nokcell: "0853884888",
    nokemail: " ",
    image: "images/male.jpeg"
}
];

app.controller("mainController", function($scope){
 $scope.users = data;
});

app.controller('infoController', ['$scope', 'users', '$routeParams', function($scope, users, $routeParams) {
  users.success(function(data) {
    $scope.info = data[$routeParams.id];
});
}]);

请帮助我。

1 个答案:

答案 0 :(得分:0)

$index仅可从ng-repeat内部访问。

将ng-repeat改为a-tag

<a ng-repeat="user in users | orderBy: order | filter:expression" ng-href="#!/info/{{$index}}">        
    <div class="info">
        <div class="img">
            <img ng-src="{{user.image}}">
        </div>
        <div class="text">
            <h3 style="color: #007acc;"> Student Details For:</h3>
            <h2>{{user.name}}</h2>
        </div>
    </div>
</a>

然后应该在加载控制器时直接设置$scope.info,而不要等待'users'的成功功能(那是什么?)

尝试一下

app.controller('infoController', ['$scope', '$routeParams', 
function($scope, $routeParams) {
    $scope.info = data[$routeParams.id];
}]);