Syed Danish Ali
Syed Danish Ali

Reputation: 391

Setting controller dynamically Angular

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?

Upvotes: 0

Views: 31

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

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.
        }
    }
};

Upvotes: 1

Related Questions