What I tried :
$routeProvider
.when('/paintings',
{
controller: 'imageController' , 'getPaintingImages'
templateUrl: 'paintings.html'
})
.when('/foods',
{
controller: 'imageController' , 'getFoodImages'
templateUrl: 'food.html'
})
I wanted getPaintingImages and getFoodImages to get the list of paintings/foods from a factory, and imageController to manipulate the images. But only first controller gets called.
Earlier I wrote code to get the images in imageController only,
myWebsite.controller('imageController', function imageController($scope, getPaintings){
$scope.images = getPaintings.images(); // but need to make this work for different set of images
$scope.imageCount = countObjectElements($scope.images);
$scope.selectedImage = $scope.images[0];
$scope.selectedImageIndex = 0;
$scope.updateSelectedImage = function(img) {
$scope.selectedImage = img;
$scope.selectedImageIndex = $scope.images.indexOf(img);
};
$scope.updateSelectedImageIndex = function(val) {
alert($scope.imageOf);
if($scope.selectedImageIndex <= 0)
$scope.selectedImageIndex = $scope.imageCount;
$scope.selectedImageIndex = ($scope.selectedImageIndex + val) % $scope.imageCount;
$scope.selectedImage = $scope.images[$scope.selectedImageIndex];
};
});
As I am a beginner in angularJS, I am not sure if creating multiple controllers a solution for re-using imageController ? If yes how to do this, if not how to re-use imageController to work for different set of images. In case of functions, re-use of function is generally by parameter passing. But here I am wondering how can a controller take parameters as it gets called for a view internally ?
getPaintingImages and getFoodImages are using a factory to get the images you say. It sounds like you could use something like resolve: in the routeProvider so that the images the imageController needs are there for them when it is called.
Something like (assuming your getPaintings and getFoods are services/factory and get images are something that returns a $promise that resolve into images i.e. $http request):
$routeProvider
.when('/paintings', {
controller: 'imageController',
templateUrl: 'paintings.html',
resolve: {
images: function($q, getPainting) {
getPainting.images();
}
}
})
.when('/foods', {
controller: 'imageController',
templateUrl: 'food.html',
resolve: {
images: function($q, getFoods) {
getFoods.images();
}
}
})
Then you could just access images like:
myWebsite.controller('imageController', ['$scope', 'images', function ($scope, images){
...
}]);
How about making imageController the parent:
<body ng-controller="imageController">
<div ng-view></div>
</body>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With