简体   繁体   中英

Using angular routeProvider with controller

Please consider the this code where the routeProvider is needed to inject page(n).html in ng-view.

In addition to the console error:

unknown provider: $routeProviderProvider <- $routeProvider

The argument to function routeIt is the name of the page to navigate to, How can I mix a conditional switch with routeProvider.when in order to call the page matching the argument in the most efficient manner? Thanks

 (function () { 'use strict'; angular .module('appModule') .controller('MainMenuCtrl', ['$scope', '$http', 'TogglerFactory', '$routeProvider', MainMenuCtrl]); function MainMenuCtrl($scope, $http, Toggler, routeProvider) { $http.get('models/mainMenu.json').then( function (response) { $scope.menuItems = response.data; }, function (error) { alert("http error"); } ) function routeIt (page) { routeProvider .when('/page1', { url: "/page1", templateUrl: 'views/page1.html', controller: 'Page1Ctrl' }) .when('/page2', { url: "/page2", templateUrl: 'views/page2.html', controller: 'Page2Ctrl' }) } $scope.itemClicked = function (item){ Toggler.menuToggle(); routeIt(item); } } })(); 

Service providers aren't available for injection in run phase (ie anywhere but provider services and config blocks). It is possible to make route provider injectable and configure it after config phase,

app.config(function ($provide, $routeProvider) {
  $provide.value('$routeProvider', $routeProvider);
});

And controllers aren't the best places to implement any logic (eg route hot-plug).

Ok you're using your routeProvider wrong you need to configure your routes inside .config blocks

angular.module('myApp', [])
.config(function($routeProvider, $locationProvider) {
    $routeProvider
       .when('/page1', {
             url: "/page1",
             templateUrl: 'views/page1.html',
             controller: 'Page1Ctrl'
       }
 })

If you want to change the url from your controller use $location.path('/page1'); inside your controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM