如何在循环外打印(按ng键单击)ng-repeat项?

时间:2015-04-28 20:47:36

标签: angularjs angularjs-ng-click

我有一个简单的对象数组michael@michael-desktop:/opt/PhpstormProjects/app_april_2015$ gulp watch [23:05:03] Using gulpfile /opt/PhpstormProjects/app_april_2015/gulpfile.js [23:05:03] Starting 'watch'... [23:05:03] Finished 'watch' after 13 ms (请参阅我的jsfiddle)。我使用ng-repeat打印所有名称,我想在ng-repeat循环之外打印我点击的名称的年龄。

{name,age}

2 个答案:

答案 0 :(得分:1)

您应该传递对象本身$index,而不是传递friend,然后您可以阅读他的信息。

快速重构:http://jsfiddle.net/par2nrd4/4/

答案 1 :(得分:0)

以下代码应该对你有用....

<body ng-app="myapp">
<div ng-controller="MyController" >
<ul>
<li ng-repeat="friend in myData.friends" ng-click="myData.doClick(friend.name)">{{friend.name}}</li>
</ul>
<p>Age :</p>
<p>{{ageval}}</p>
</div>
<script>
angular.module("myapp", []).controller("MyController", function($scope) {
    $scope.myData = {};
    $scope.myData.friends = [{ name: "Al",age:26}, { name: "Mike",age:21}, { name: "Brian",age:46} ];
    $scope.myData.doClick = function(item) {
        for (i = 0; i < $scope.myData.friends.length; i++) {
            if (item == $scope.myData.friends[i]["name"]) {
                $scope.ageval = $scope.myData.friends[i]["age"];
            }
        }
    }
} );
</script>
</body>