Monday 5 November 2018

angularjs - Passing data from one view to another using UI-Router

I am trying to figure out the best way to pass data from one controller to another using UI Router. I have two views populated with data from two different APIs. View 1 contains a ng-repeater with a list of restaurants from an API endpoint (returns name, image and ID). View 2 contains the restaurant information from another API endpoint (returns description, menu and ID). A user clicks on a restaurant in the View1 list and it opens that restaurant in View 2 with the description etc by passing the restaurant ID. The problem is the API endpoint in View 2 does not contain the restaurant name and image. So in order to display the name and image I had to pass them in the link like this...



{{restaurant.Name}}


And then that is handeled by the controller for View 2 like this



(function() {

'use strict';

angular.module('components.restaurantProfile', [])
.controller('RestaurantProfileController', function(resolvedRestaurantId, Restaurants, $stateParams) {
var vm = this;

vm.name = $stateParams.name;
vm.image = $stateParams.image;

Restaurants.findByRestaurantId(resolvedRestaurantId)

.then(function(result) {
vm.restaurant = result
})
})
.config(function($stateProvider) {
$stateProvider
.state('restaurantProfile', {
url: '/restaurant/:id',
templateUrl: 'components/restaurant-profile/View2.html',
controller: 'RestaurantProfileController as pc',

params: {
name: '',
image: ''
},
resolve: {
resolvedRestaurantId: function($stateParams) {
return $stateParams.id;
}
}
});

});
})();


This works, but it doesnt feel right. Especially if I need to pass more params, the ui-sref link would become very long. Is there a better way to pass the name/image from the selected restuarant in View1 to View2? Is it possible to pass the selected restaurant object from the repeater to another view?



Also, if it helps, the service called Restaurants which is injected into RestaurantProfileController above is also shared with View1 controller. Could I pass it through there?



Apologies for the long post - I wanted to make sure I was clear. Thanks.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...