我有两个数组,分别是用户和就业:
I have two arrays, Users and Employments like so:
Users = [{id:1, name: "ryan"}, {id:2, name:"Julie"}] Employments = [{user_id: 1, title: "manager"}, {user_id: 2, title: "Professor"}]我想以ng-repeat的形式显示Jobs数组:
I'd like to display the Employments array in an ng-repeat like so:
<li ng-repeat="employment in Employments"> {{employment.user.name}} </li>如何将用户"数组映射到就业"数组?
How do I map the Users array to the Employments array?
推荐答案如果您希望根据id显示员工姓名,最简单的方法是将该id传递给函数并返回姓名,如下所示
If you want the employee name to get displayed based on id, the simplest way is just pass that id to a function and return the name, like as shown below
工作演示
Working Demo
html
<div ng-app='myApp' ng-controller="ArrayController"> <li ng-repeat="employment in Employments">{{getEmployeeName(employment.user_id)}} </li> </div>脚本
var app = angular.module('myApp', []); app.controller('ArrayController', function ($scope) { $scope.Users = [{ id: 1, name: "ryan" }, { id: 2, name: "Julie" }]; $scope.Employments = [{ user_id: 1, title: "manager" }, { user_id: 2, title: "Professor" }]; $scope.getEmployeeName = function (empId) { for (var i = 0; i < $scope.Users.length; i++) { if ($scope.Users[i].id === empId) { return $scope.Users[i].name; } }; }; });更新2
如果要在就业"数组中嵌入User数组,请尝试以下操作
If you want to embed the User array in the Employments array, try the following stuff
$scope.Users = [{id: 1, name: "ryan"}, {id: 2, name: "Julie"}]; $scope.Employments = [{user_id: 1, title: "manager"}, {user_id: 2, title: "Professor"} ];用于通过添加用户属性来平整就业机会"数组的代码
code for flattening Employments array by adding User properties
angular.forEach($scope.Users, function (user, userIndex) { angular.forEach($scope.Employments, function (employee, employeeIndex) { if (employee.user_id === user.id) { employee.name = user.name; } }); });输出
$scope.Employments = [ { user_id: 1, title: "manager", name: "ryan" }, { user_id: 2, title: "Professor", name: "Julie" } ]工作演示
Working Demo
更新3
如下所示从$scope.Users和$scope.Employments
$scope.employees = []; angular.forEach($scope.Employments, function (employee, employeeIndex) { var employeeObject = {}; employeeObject.title = employee.title; angular.forEach($scope.Users, function (user, userIndex) { if (employee.user_id === user.id) { employeeObject.user = user; } }); $scope.employees.push(employeeObject); });输出
[ { title: "manager", user: { "id": 1, "name": "ryan" } }, { title: "Professor", user: { "id": 2, "name": "Julie" } } ]工作演示
Working Demo
更多推荐
AngularJS将数组映射到另一个数组
发布评论