Kamal Kamal - 5 months ago 17
AngularJS Question

routing using $routeParams in angular

Hi friends I'm new into angular and want to develop a Single page application. For this I create a service to call data which is working fine and also create a controller for show user list. Facing problem when using routing. I want when user click on anyone tab from list page then user will land to detail page with detail of that user which was clicked in list page... Please check my code below

Getting this error in console with this code

userData.userslist(...).find is not a function


controller.js

var myApp = angular.module('assignment', ['ngRoute']);

myApp.service('userData', ['$http', function($http){
return{
userslist : function(){
return $http({'url' : 'js/data.json', 'method' : 'GET'}).then(function(response){
return response.data;
}, function(data){
console.log('some error')
})
}
}
}]);


myApp.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'user-list.html',
controller: 'users'
}).
when('/:username', {
templateUrl: 'detail.html',
controller: 'userdetail'
}).
otherwise({
redirectTo: '/'
});
});



myApp.controller('users', ['$scope', '$http', 'userData', function($scope, $http, userData){
userData.userslist().then(function(data){
$scope.items = [];


angular.forEach(data.data.bst_users, function(item){
$scope.items.push(item);

})

})
}]);



/*>>>>>Problem is here<<<<<<*/

myApp.controller('userdetail', ['$scope', '$routeParams', 'userData', function($scope, $routeParams, userData){
console.log($routeParams.username);

userData.find($routeParams.username, function(found){

$scope.user = found;
})

console.log(scope.user)

}])


/*******Filters*******/

myApp.filter('removeSpace',function() {
return function(input) {
if (input) {
return input.replace(/\s+/g, '-');
}
}
});

Answer

The service does not have any method find() that takes username as an input parameter. Currently, service returns a list as userlist()

Probably need to make an explicit call again to service to fetch the list of users and then filter it by username.

myApp.controller('userdetail', ['$scope', '$routeParams', 'userData', function($scope, $routeParams, userData){

  console.log($routeParams.username);

  userData.userslist().then(function(data){
     $scope.items = [];
     angular.forEach(data.data.bst_users, function(item){
       $scope.items.push(item);

       //Find User here
       if(item.username == $routeParams.username) {
          $scope.user = item;
       };

     });
  });
}]);

Alternatively, when changing the route , you can store the $scope.items in ng-cookies and fetch this list in the controller to filter by username.