Bomin
Bomin

Reputation: 1667

Change controller for a view in angular

Is there any way for me to change a view's controller in angular?

angular.module('app', [
  'ngRoute'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/', {
    templateUrl: 'views/home/index.html',
    controller: 'home',
    replace: false
  })
  $routeProvider.otherwise({redirectTo: '/'});
}]);

What I'm trying to do is give another controller for index.html in runtime.

Upvotes: 0

Views: 60

Answers (2)

Smrutiranjan Sahu
Smrutiranjan Sahu

Reputation: 7631

angular.module('myapp', []).config(function($provide, $routeProvider) { $provide.factory('$routeProvider', function () { return $routeProvider; }); }).run(function($routeProvider, $http) { $routeProvider.when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }).otherwise({ redirectTo: '/' }); $http.get('/dynamic-routes.json').success(function(data) { $routeProvider.when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }); // you might need to call $route.reload() if the route changed $route.reload(); }); });

Upvotes: 0

Magnus Gudmundsson
Magnus Gudmundsson

Reputation: 556

Instead of messing with the view, define a couple of views, and change the current configuration with state.

ex: view1 has controller#1 and url#1 view2 has controller#2 and url#1

Read this blog for a more thorough explanation: http://txt.fliglio.com/2013/05/angularjs-state-management-with-ui-router/

Upvotes: 1

Related Questions