agon024 agon024 - 2 months ago 7
AngularJS Question

Grabbing ID from a controller and adding to another controllers API call

here is my initial module:

angular.module('ngApp', [])
.factory('authInterceptor', authInterceptor)
.constant('API', 'http://myserver.com/ecar/api')
.controller('task', taskData)

function taskData($scope, $http, API) {
$http.get( API + '/tasks' ).
success(function(data) {
$scope.mainTask = data;
console.log(data);
});
}


This returns a JSON array that contains a key "CAR ID: 1297" or whatever for each item in the array. I need to grab that id and store it in a variable somehow and recall it in another controller. The reason is so that when this car is displayed with minor info they can click "view details" and it will open another page that will display all the details of the car based on the id.

Maybe something like this:

angular.module('ngApp', [])
.factory('authInterceptor', authInterceptor)
.constant('API', 'http://myserver.com/ecar/api')
.controller('task', taskData)
.controller('carDetails', carDetails)

function taskData($scope, $http, API) {
$http.get( API + '/tasks' ).
success(function(data) {
$scope.mainTask = data;
console.log(data);
});
}

function carDetails($scope, $http, API) {
$http.get( API + '/car/$id' ).
success(function(data) {
$scope.mainTask = data;
console.log(data);
});
}


I just need to grab the "CAR ID" from the "taskData" function that the JSON sends and add it into the "carDetails" functions API call (as you see above). So I need to obviously create a variable (such as $id) to pass to the second function but I don't know how.

Can anyone help me?

Answer

Got this working based on this post - Inserting JSON ID key into ng-click directive and then pass that into another controller

Here is the script that works:

ngular.module('ngApp', [])
.service('CarDetailService', CarDetailService)
.controller('task', taskData)
.controller('carDetails', carDetails);

CarDetailService.$inject = ['$http', 'API'];
function CarDetailService($http, API) {
  var CarDetailService = this;
  CarDetailService.setCar = function(carId) {
    CarDetailService.carId = carId;
  };

  CarDetailService.getCar = function() {
    return $http.get(API + "/car/" + CarDetailService.carId);
  };
}

taskData.$inject = ['$scope', '$http', 'API', 'CarDetailService'];
function taskData($scope, $http, API, CarDetailService) {
  $http.get( API + '/tasks' ).
  success(function(data) {
    $scope.mainTask = data;
    console.log(data);
  });

  $scope.selectCar = function(carId) {
    CarDetailService.setCar(carId);
    $location.url('/car-details-route');  //go to details page
  };
}

carDetails.$inject = ['$scope', 'CarDetailService'];
function carDetails($scope, CarDetailService) {
  CarDetailService.getCar().success(function(details) {
    $scope.details = details;
  });
}
Comments