Angularjs Use injectect module's controller in route definition

668 Views Asked by At

I'm new to angular and I'm trying to modularlize my app.

My main module gets some other module and I want to use the controller of the injected module in my route definition. Some simple example would be very helpful!

This does not work:

var app = angular.module('Contacting_App', ['LeadLookup']);

app.config(['$routeProvider', function($routeProvider) {
                    $routeProvider.
                        when('/main', 
                            {controller: 'MainCtrl', 
                            templateUrl: 'apex/f42_Contacting_Main'}
                        ).
                        when('/lead', 
                            {module: 'LeadLookup',
                            controller: 'LeadLkpCtrl', 
                            templateUrl: 'apex/f42_Lead_Lookup'}
                        ).
                        otherwise(
                            {redirectTo: '/main'}
                        );
                }]);
1

There are 1 best solutions below

7
On

This tutorial page may point you in the correct direction docs.angularjs.org/tutorial/step_07

The main things you should look at are:

Module

var phonecatApp = angular.module('phonecatApp', [
  'ngRoute',
  'phonecatControllers'
]);

routeProvider

phonecatApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/phones', {
        templateUrl: 'partials/phone-list.html',
        controller: 'PhoneListCtrl'
      }).
      when('/phones/:phoneId', {
        templateUrl: 'partials/phone-detail.html',
        controller: 'PhoneDetailCtrl'
      }).
      otherwise({
        redirectTo: '/phones'
      });
  }]);

Controllers

var phonecatControllers = angular.module('phonecatControllers', []);

phonecatControllers.controller('PhoneListCtrl', ['$scope', '$http',
  function ($scope, $http) {
    $http.get('phones/phones.json').success(function(data) {
      $scope.phones = data;
    });

    $scope.orderProp = 'age';
  }]);

phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams',
  function($scope, $routeParams) {
    $scope.phoneId = $routeParams.phoneId;
  }]);