I have an array with JSON objects in my $scope.users which is working correctly. I'm now trying to set up a "detail" page for an individual user by filtering the users list to get a single user.
I've been close for an excruciating amount of time, and for some reason I can't find documentation or any examples of how to do what I'm doing. Maybe this isn't the correct way to do this in Angular and/or maybe I'm not searching for the right thing?
I've tried getting the object based on userId from the list in the controller, and I've tried passing a resolve in the state, but I didn't get either method to work. What is the best way to go about getting the single user with id of $stateparams.userId?
Everything else is working correctly (ie all the routing, getting the users on #/users).
// routing section of app.js
// Routing
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'static/partials/main/home.html'
})
.state('users', {
url: '/users',
templateUrl: 'static/partials/accounts/users.html',
controller: 'UserController'
})
.state('profile', {
url: '/users/{userId}',
templateUrl: 'static/partials/accounts/profile.html',
controller: 'UserController'
});
// controller.js
var rlGlobalControllers = angular.module('rlGlobalApp.controllers', []);
rlGlobalControllers.controller('UserController', function($scope, $stateParams, $filter) {
var userId = $stateParams.userId;
$scope.users = [
{
'id': 1,
'name': 'Shadrack'
},
{
'id': 2,
'name': 'JP'
},
{
'id': 3,
'name': 'Adam'
}
];
// $scope.user = ???
});
# profile.html
<div ng-include src="'/static/partials/shared/header.html'"></div>
<div class="container">
<div class="row">
<p>users data: {{ users }}</p>
<p>user data: {{ user }}</p>
</div>
</div>
User Array.prototype.filter
method to find objects satisfying criteria:
$scope.user = $scope.users.filter(function(user) {
return user.id === userId;
})[0];
This is the most natural way to solve it. If however your users
array is very large (like millions, for example (hope it's not)) then for-loop-break solution of juunas is preffered as more effective.
You could just do this in the controller:
for(var i = 0; i < $scope.users.length; i++){
if($scope.users[i].id === userId){
$scope.user = $scope.users[i];
break;
}
}
var output = [],
keys = [];
Array_Value.forEach(function (item) {
var key = item["Field name"];
if (keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
this.Title = output;
Instead of Array_value and field name, give your data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.