Is it possible to exchange route system ($route) in the same URL? Angular JS

Asked

Viewed 945 times

2

I want, from a constant (configuration) change controller or Directive that is in the same URL.

For example, imagine I’m on the home page and then we have the path "/" ok. However, depending on the setup the guy can change it. I’ll put an example:

angular.module('meuModulo')
  .config(['$routeProvider’, ‘go.svc.config’,  function($routeProvider, config) {
    $routeProvider
    .when('/', {
      templateUrl: 'directives/directive1.html',
      controller: function() {
    var conf = config.home;

    if (conf === ‘musica’) {
        return 'controllers/meuControllerMusica',
    } else {
        return ‘controllers/meuControllerHomePage';
    }
   };
  })
}]);

The idea here would be: According to a specific configuration, I would change the Controller.... so far perfect.

The problem that the .config in this case accept ONLY the $routerProvider, then I can’t do what I want.

The closest solution I arrived was to leave a fixed controller (without being a Function) and within it do something like:

$route.current.controller = 'meuControllerMusica';
$route.reload();

The problem that if I do this, it is in infinite loop, because it will always stay in the old controller, makes the switch and gives the Reload.

Has anyone gone through anything like it or have any other idea?

  • Why do you want to switch 2 controllers in 1 view? Why not create one view per controller? Add more code and explain the purpose better. At.

  • I don’t know much about angular, but controller of routeProvider is string? if it is, add () at the end of its controller function so that it is assigned the function result and not the function type object

2 answers

1

You can use ng-switch to exchange a DOM element that contains a directive.

For example:

angular.module('meuModulo')
  .config(['$routeProvider’, ‘go.svc.config’,  function($routeProvider, config) {
    $routeProvider
    .when('/', {
      templateUrl: 'directives/directive1.html',
      controller: 'main'
   };
  })
}])
    .controller('main', ['$scope', 'go.svc.config', function($scope) {
        var conf = config.home;

        if (conf === ‘musica’) {
            $scope.showView = 'musica';
        } else {
            $scope.showView = 'home';
        }
}]);
;

In view

<div ng-controller="main">
    <div ng-switch on="showView">
      <div  ng-switch-when="home" ng-controller="meuControllerHomePage">Settings Div</div>
      <div  ng-switch-when="musica" ng-controller="meuControllerHomePage">Home Span</div>
      <div  ng-switch-default>default</div>
  </div>
</div>

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.