0

I have a query related to setting controllers at runtime. I want something like:

.state{'app.thisState',
   url: '/thisUrl',
   views:{
     templateUrl: 'templates/some_template.html',
     controller: 'XYZCtrlr' //This is where I want to set different controllers depending on the scenario.
   }};

How can we set controllers at runtime?

1 Answer 1

1

You could use controllerProvider option of ui-router state

.state ('app.thisState', { //<-- correct syntax here
    url: '/thisUrl',
    views: {
        templateUrl: 'templates/some_template.html',
        controller: 'XYZCtrlr',
        controllerProvider: function($stateParams) { //<-- add dependencies here
            //perform logic here
            var ctrlName = $stateParams.type + "Controller";
            return ctrlName; //return string name here, which will the name of controller.
        }
    }
};
Sign up to request clarification or add additional context in comments.

3 Comments

Can you please elaborate var ctrlName = $stateParams.type + "Controller";. What is happening in this line? Sorry I'm a newbie in angular
Basically just for demonstration, I did inject a $stateParams dependency & then I'm reading state parameter & creating controller name.. I wrote that code just for demo, with comments
I get it. Is it possible to have $rootScope dependency here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.