What is the best way to assign multiple controllers to a single view in angularJS?

My Attempt:

 $routeProvider
     .when('/paintings',
         {
             controller: 'imageController' , 'getPaintingImages'
             templateUrl: 'paintings.html'
         })
     .when('/foods',
         {
             controller: 'imageController' , 'getFoodImages'
             templateUrl: 'food.html'
         })

I attempted to use getPaintingImages and getFoodImages to retrieve the list of paintings/foods from a factory, with imageController handling image manipulation. However, only the first controller is being called.

Prior to this, I had written code in imageController like this:

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];
    };
});

Being new to angularJS, I'm unsure if creating multiple controllers is the solution for reusing imageController. If it is, how can I achieve this? If not, how can I modify imageController to handle different sets of images effectively? When it comes to functions, parameter passing allows for reusability. But in the case of controllers, I am puzzled on how parameters can be passed as they are internally called for a view.

Answer №1

Utilizing a factory to retrieve images for functions like getPaintingImages and getFoodImages seems like a good approach. Implementing resolve in the routeProvider could ensure that the necessary images are available for the imageController when it's invoked.

Here is an example setup (assuming getPaintings and getFoods are services/factories, and the getImage functions return a $promise that resolves with the images from an $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();
            }
        }
    })

After setting this up, the images can be accessed easily within the imageController:

myWebsite.controller('imageController', ['$scope', 'images', function ($scope, images){
    ...
}]);

Answer №2

Have you considered setting imageController as the main controller:

<section ng-controller="imageController">  
    <div ng-view></div>
</section>

Answer №3

Placing a controller on a view triggers the creation of an isolated scope specifically for that view, preventing the existence of multiple isolated scopes within the same view which would lead to errors. Your choices are limited in this scenario - either assign the controller to the parent element or invoke the imageController function from the initial controller and pass along the $scope.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transferring information to an outside document using Ajax

My code works perfectly when I use this: ajax.open("post","a.php",true); However, the problem arises when I attempt to send data to an external file like this: ajax.open("post","http://www.example.com/a.php",true); Unfortunately, it doesn't work i ...

Is the JSON object sent over an AJAX call getting corrupted during a POST request?

While conducting tests on this application, The browser is sending a json as an array of approximately 500 objects via POST method. Upon inspecting the received json using a PHP server and debugger(xdebug), It appears that there are more elements in ...

The test suite encountered an error (EBUSY: resource busy or locked) and unfortunately failed to run at Nx version 14.5.10 and Jest version 27.5.1. It seems there was an

I have recently upgraded my NX Monorepo from version 13 to 14, and everything seems to be working fine except for the Jest migration. I keep encountering this error even after trying various solutions like clearing the cache, deleting node_modules, and rei ...

Permission to create a database in 'master' database on SQL Server 2008 R2 denied

I am attempting to create a simple login demo similar to http://www.codeproject.com/Articles/1032226/CRUD-Operation-in-ASP-NET-MVC-and-AngularJS However, when the page loads, I encounter an error: 'create database permission denied in database &ap ...

What is the best way to synchronize the image dimensions and source when dynamically loading images?

I am facing an issue with a function that updates images by altering the src and css (width/height) of an IMG tag within the document. Below is a simplified example to demonstrate the problem: updateImage = function(src, width, height) { $("#changeMe"). ...

Is it accurate that JavascriptResult displays javascript on the page in a string format?

I am new to .NET MVC and have been experimenting with different return types in MVC. However, I am having trouble getting the JavaScriptResult to work. In my controller, I have the following code: public ActionResult DoSomething() { string s = ...

Creating an Ionic v4 alert box that redirects users to different pages

I am facing an issue with my ion-alert component where I have set up a message with two options, "To Myself" and "To Someone", that should act like buttons and route to different pages in the application. However, using (click) events or [routerLink] on th ...

The npm http package exclusively includes a package.json without any accompanying JavaScript files

After installing an npm package that listed 'http' as a dependency, I also installed 'http'. However, all npm downloaded for 'http' was a package.json file that referenced a non-existent index.js file. Could it be that the ind ...

What is the best way to transmit a JSON object to REST services using Angular?

Whenever I attempt to send the JSON object to REST services, I encounter an error that looks like this: http://localhost:8080/api/v1/cardLimit 400 (Bad Request); JSON Object Example: public class GameLimit implements Serializable { private stati ...

Utilizing the 'as' prop for polymorphism in styled-components with TypeScript

Attempting to create a Typography react component. Using the variant input prop as an index in the VariantsMap object to retrieve the corresponding HTML tag name. Utilizing the styled-components 'as' polymorphic prop to display it as the select ...

Determine whether there is greater available space above or below a specific element within the DOM

I'm looking to create a dynamic layout where an input field is accompanied by a list in a div, positioned either above or below depending on available space. This setup needs to account for the fact that the input field could be located anywhere on th ...

Transmit JSON data from the client to the MarkLogic Server device

Hello everyone, hope you are all doing well. I am a beginner in Marklogic and recently managed to set up a rest api on my local machine. Following the given example, I used curl to send/create documents in the database. Now, my query is how can I access/ ...

Updating a table dynamically after a form submission using jQuery, Ajax, and PHP without needing to refresh the page

My current setup involves an ajax form along with a table. Here is the ajax code I am using: $(function () { $(".submitann").click(function () { var title = $("#title").val(); var announcement = $("#announcement").val(); var d ...

Having trouble storing JSON data from an $http.get request in AngularJS to a variable or cache?

I'm facing an unusual issue with my AngularJS code. I am trying to retrieve data from a Rest Webservice and though the retrieval is successful, I am unable to save the JSON data to an object. Here is a snippet of my code: services.service('custo ...

The PHP equivalent of converting data to a JSON string, similar to the

When working with PHP's json_encode($array), I've noticed that diacritics can sometimes get messed up. However, if I update my database column to type text and pass javascript-created JSON over HTTP, everything appears fine. The issue arises when ...

Adjust the form action and text input name according to the selected radio input

Seeking assistance with the following code, can someone help? $(document).ready(function() { $('#searchform').submit(function() { var action = ''; if($('.action_url').val() == 'l_catalog') { ...

Could Express be considered the most reliable and efficient application framework for NodeJS?

While I have some experience with Express, I haven't explored many other Node-based web application frameworks. It's clear that Express is lightweight and versatile, but my usage has been limited to small experimental projects rather than large-s ...

Showing JSON information fetched from an AJAX request within an HTML page

I've been working on a project and I'm almost there with everything figured out. My main challenge now is to display an array of items on a web page after making an ajax call. Below is the code snippet I currently have: JQuery Code: var su ...

The AngularJS Cross-Origin Resource Sharing (CORS) Policy

Our team is currently working on a web application using AngularJS that requires calling REST API services from another application. However, due to it being a cross domain request, we are facing difficulties in making the calls and receiving the following ...

Establishing relationships with Sequelize between tables in different schemas

Currently, I am working on a project that involves using Sequelize and PostgreSQL as the database. In this project, I have implemented dynamic schema creation whenever a new user registers on the website. Specifically, I have a table called user_credentia ...