我是angular.js的新手。我正在使用具有分拣机列表的用户列表,当我单击用户名时,所选用户电话号码应显示在所选区域中。它工作正常。
我的问题是如何将第一个用户设置为默认选择。这是我的示例代码。请帮帮我。
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="js/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1>Selected View</h1>
<ul>
<li ng-repeat="userNames in users | orderBy:orderProp:direction" ng:click="select(userNames)">{{userNames.name}}</li>
</ul>
<p>selected: {{selectedUser.phone}}</p>
<script>
var myApp = angular.module('myApp', []);
//myApp.by.id('setbtn')element('h1').addClass('active');
myApp.controller('MainCtrl', ['$scope', function ($scope) {
$scope.users = [{name:'John', phone:'555-1276'},
{name:'John', phone:'555-1278'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}];
//sorting
$scope.direction = false;
$scope.orderProp = "name";
$scope.sort = function(column) {
if ($scope.orderProp === column) {
$scope.direction = !$scope.direction;
} else {
$scope.orderProp = column;
$scope.direction = false;
}
};
//selected list
$scope.select = function(phone) {
$scope.selectedUser = phone;
};
}]);
</script>
</body>
</html>
答案 0 :(得分:0)
您可以从控制器而不是html
对用户进行排序<强> HTML 强>
<li ng-repeat="userNames in getSortedUsers()"
ng:click="select(userNames)">{{userNames.name}}</li>
<强>控制器强>
$scope.getSortedUsers = function () {
// Use $filter service. You have to add $filter as dependencies in controller
var users = $filter('orderBy')($scope.users, $scope.orderProp +
':' + $scope.direction);
// Set first user as selected user
$scope.selectedUser = users[0];
return users;
}
答案 1 :(得分:0)
只需在控制器中使用此功能即可设置默认用户的电话号码
$scope.selectedUser = $scope.users[0];
答案 2 :(得分:0)