Creating a Dynamic Controller with Dynamic Parameters in AngularJS

For my project, I am using requirejs, angularamd, and ui.bootstrap. When working with a popup form, I utilize $uibModal from ui.bootstrap. However, I am facing an issue where I cannot pass a parameter "items" from resolve. How can I dynamically inject parameters for a controller that has been resolved?

function open(size, parentSelector) {
        var parentElem = parentSelector ?
          angular.element($document[0].querySelector('.grid ' + parentSelector)) : undefined;

        var modalInstance = $uibModal.open({
            animation: vm.animationsEnabled,
            ariaLabelledBy: 'modal-title',
            ariaDescribedBy: 'modal-body',
            size: size,
            appendTo: parentElem,
            templateUrl: 'Views/Shared/ColSetting.html',
            resolve: {
                load: ['$q','$rootScope',function ($q, $rootScope) {
                    var loadController = "Views/Shared/ColSettingController";
                    var deferred = $q.defer();
                    require([loadController], function () {
                        deferred.resolve(items);
                        $rootScope.$apply();
                    });
                    return deferred.promise;
                }]
            }
        });

Here is the controller that needs to be called.

'use strict';

define(['application-configuration', 'ajaxService'], function (app) {
function ColSettingController(items) {
    var vm = this;

    //vm.content = $rootScope.content;

    vm.ok = function () {
        //$uibModalInstance.close(vm.selected.item);
    };

    vm.cancel = function () {
        //$uibModalInstance.dismiss('cancel');
    };
}

app.register.controller("ColSettingController", ColSettingController);
});

Answer №1

As per the ui.bootstrap documentation, the resolve property is expected to be a map object. This map object contains key/value pairs such as:

  • key{string}: this represents the name of a dependency that will be injected into the controller.
  • factory - {string|function}: If the value is a string, it functions as an alias for a service. If the value is a function, it gets injected and the returned value is considered as the dependency. In case the result is a promise, it gets resolved before the controller is instantiated and the value is injected into the controller.

In your current scenario, you are using load, but your controller expects items to be injected. I'm assuming you're encountering an error stating that it can't locate items, correct? This is due to the fact that you are injecting load.

You should modify the name of the property in the resolve section, replacing load with items.

resolve: {
    //replace 'load' with 'items' here
    items: [....rest of your code goes here....]

Additionally, it is advisable to use the $inject property before declaring controllers/components and others, similar to the following example:

function ColSettingController(items) {
    //some code here
}

ColSettingController.$inject = ['items'];

app.register.controller("ColSettingController", ColSettingController);

Hope this information proves to be helpful

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

Interactive preview of PDFs with pdf.js adaptation

How can I update my PDF preview when resizing the window? Currently, the canvas resizes but the PDF preview remains the same size. I am struggling to find a solution for this. var myState = { pdf: null, currentPage: 1, zoom ...

Issue encountered while attempting to host an ejs file using Express in Node.js

I'm encountering an issue while attempting to serve an .ejs file using express. The error I'm getting is as follows: Error: No default engine was specified and no extension was provided. at new View (C:\development\dashboard& ...

Tips for setting an identification value within mongodb?

Currently, my focus is on utilizing node.js and mongoose. I am in the process of developing a REST API to showcase my User model: var userSchema = new Schema({ _id: {type:Number}, username: {type:String}, age: {type:Number}, genre:{type: Number,ref:&a ...

Trigger AngularJS functionality upon the completion of loading a Partial routed by Express

I'm fairly new to AngularJS and recently ran into an issue that's been keeping me up at night... Our application is built on node.js and express, with all partial routing handled by Express. The problem I'm facing is this: Whenever I load ...

Is there a way to dismiss a modal window from the parent?

How can I close a modal window from its parent? This task seems quite challenging to accomplish. Essentially, I am opening a non-modal window. In some cases, the user may open a modal window from this non-modal window. If I close the non-modal window, I al ...

An unforeseen repetition of jQuery Ajax calls

I'm currently working on an application that utilizes ajax calls to load content. However, I've encountered a situation where an ajax call goes into a loop but seems to end randomly. Below is the code sequence starting from a double click event l ...

npm encounters difficulty in initiating the server

I encountered some errors after running npm start in my angular project directory. It was working fine yesterday, but today when I entered the npm start command in my cmd prompt, it started showing errors: This is how my package.json file looks like: { ...

Having trouble getting Three JS to render files in scene 1 format 2?

Currently, I am working on an application that showcases 3D models imported from various modeling software. Specifically, I have an STL file exported from CatiaV5 and a DAE file exported from the latest version of Sketchup. Initially, I was able to succes ...

Guide to looping through a map arraylist in JavaScript

Here is a sample map arraylist. How can I access this arraylist using JavaScript from within pure HTML? And how can I iterate over this list? <%@page import="org.json.simple.JSONObject"%> <%@page import="org.json.simple.JSONArray"%> <% JSON ...

AngularJS, sort through "afoo" excluding "foo"

I am attempting to implement a filter within an ng-repeat Main.HTML <table> <tr ng-repeat="param in MyParam | filter: UnrequestValue"> <td>{{param.Label}}</td> </tr> </table> Main.js MyParam: ...

Executing two Ajax calls in ReactJS with different parameters can improve the efficiency of your

Why does the second Ajax call overwrite the first one, causing the results to be different each time I refresh it? In the first Ajax call, I have set tests: [], testsHistories: [] in the setState function. However, the second Ajax call only sets the stat ...

Guide: How to transfer the output from MongoDB in Node.js to AngularJS?

Currently, I am using Node.js to query my data from a MongoDB database. However, I am facing an issue where the data is not being sent out as expected when running this particular function. var findIco = function(db, callback) { var cursor = db.collec ...

FadeOut Television static on Canvas after a period of inactivity

Is there a way to smoothly fade out the TV noise after a specific timeout period? I found this code snippet on Stack Overflow that seems to address a similar issue: var canvas = document.getElementById('canvas'), ctx = canvas.getContext( ...

Incorporating a specific time to a JavaScript date object

In my Angular application, I am facing an issue with adding a time to a date. The appointmentDate from the date picker returns a JavaScript date while the appointmentTime is selected from a dropdown with options like "8:00", "8:30", "9:00", etc. I'm ...

JQuery appended Bootstrap Modal to Body, but it refuses to close

After going through the process of appending the modal to the body and getting the text box working, I encountered an issue when trying to close it on the AJAX success event - none of my attempted solutions seem to be effective. var id; var refundAmount ...

What could be causing redux.props.reducer to return undefined?

I recently encountered an issue with my code. I have a function in the actions folder that successfully fetches a URL using axios. However, there seems to be a problem when trying to retrieve the data from the reducer. I have a mapStateToProps function set ...

Error: Attempting to access the 'getCroppedCanvas' property of an undefined value in VueJs

I've been exploring the vue-cropperjs library, but every time I execute the code, I encounter error messages: Uncaught TypeError: Cannot read property 'getCroppedCanvas' of undefined Uncaught TypeError: Cannot read property 'replace&ap ...

Loading an ASP.net page on the client side

Can someone tell me the event for pageload on clientside? function onPageLoad() { setSelectedIndexTo(1); } I attempted to do this, however no changes occur. Appreciate any help. Thanks! ...

The Express application fails to receive a response from a Mongodb query function

In my current project, I am implementing a simple API Key authentication system. The main goal is to validate the provided key against the user's input. There is a separate file containing a function that queries the database and returns either true/ ...

Exploring the connections between Hibernate and AngularJS

I have established a connection between Travelers and Trips in Hibernate: https://i.sstatic.net/YQetP.png To create a new trip for traveler 1, I need to visit the route /frontend/#/trip-creation/1. Here, a form is available: https://i.sstatic.net/BeXnU. ...