我有一个选择框,使用ng-repeat填充数组中的数据。该数组包含名字,姓氏和用户名等信息。默认情况下,我想在选择框中显示名字和姓氏。如果这两个字符串为空,我想改为显示用户名。有谁知道实现这个目标的最佳方式?
我当前显示剩下这两个值的名字和姓氏的HTML代码为空:
<div ng-app="myApp" ng-controller="MyController as ctrl">
<select ng-model="ctrl.user">
<option ng-repeat="option in ctrl.userList" value="{{option.userName}}"
{{option.firstName}} {{option.lastName}}</option>
</select>
</div>
我的数组控制器代码段:
var userList = [{"firstName": "Steve", "lastName": "Miller", "userName": "miller"}, {"firstName": "Anne", "lastName": "Jones", "userName": "jones"}, {"firstName": "", "lastName": "", "userName": "mrX"}];
答案 0 :(得分:4)
检查表达式中的任何字符串,如果不是,则显示option.userName
<div ng-app="myApp" ng-controller="MyController as ctrl">
<select ng-model="ctrl.user">
<option ng-repeat="option in ctrl.userList" value="{{option.userName}}"
{{(option.firstName || option.lastName) ? option.firstName + ' ' +
option.lastName : option.userName }}</option>
</select>
</div>
答案 1 :(得分:2)
检查此工作代码。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('MyController', function ($rootScope, $scope, $compile) {
$scope.userList = [{ "firstName": "Steve", "lastName": "Miller", "userName": "miller" }, { "firstName": "Anne", "lastName": "Jones", "userName": "jones" }, { "firstName": "", "lastName": "", "userName": "mrX" }];
});
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="MyController">
<select ng-model="user">
<option ng-repeat="option in userList" value="{{option.userName}}">{{(!option.firstName && !option.lastName)?option.userName:( option.firstName +' '+ option.lastName)}} </option>
</select>
</div>
</body>
</html>
答案 2 :(得分:1)
这肯定会对你有所帮助:
<option ng-repeat="option in ctrl.userList" value="{{(option.firstName && option.lastName) ? option.firstName + ' '
option.lastName : option.userName}}"
{{(option.firstName && option.lastName) ? option.firstName + ' '
option.lastName : option.userName }}</option>