1

I'm developing an web app using AngularJS with uiRouter. I developed my route configuration as follows:

(function () {

    'use strict';

    var module = angular.module('app', ['ngMaterial', 'ui.router']);

    function Config($urlRouterProvider, $stateProvider) {
        $urlRouterProvider.otherwise('/');

        $stateProvider.state('Home', {
            url: '/',
            templateUrl: 'Partials/homeview.html',
            controller: 'homeCtrl'
        }).state('Table', {
            url: '/tableview',
            templateUrl: 'Partials/tableview.html',
            controller: 'tableCtrl'
        }).state('List', {
            url: '/listview',
            templateUrl: 'Partials/listview.html',
            controller: 'listCtrl'
        }).state('New', {
            url: '/new',
            templateUrl: 'Partials/new.html',
            controller: 'newCtrl'
        }).state('Edit', {
            url: '/edit/:index',
            templateUrl: 'Partials/edit.html',
            controller: 'editCtrl'
        });
    }
    Config.$inject = ["$urlRouterProvider", "$stateProvider"];

    module.config(Config);
}());

The thing in some controller passed to the view the code is duplicated, so I would like to know if there is a way to pass 2 controllers to the view at the same time or if there is a way to create a separate file with that specific part of the duplicated controller and pass it as Dependency Injection in the desired controllers.

Upalr
  • 2,140
  • 2
  • 23
  • 33
Tiago Neto
  • 379
  • 1
  • 3
  • 15

1 Answers1

1

You can't have two controllers linked to a uiRouter route. But you could certainly make a service or factory that includes your universal functionality. (See angular.service vs angular.factory for more research.)

var app = angular.module('app',[])
app.service('myFunctions',function() {
  this.addNumbers = function(a,b) {
    // calculate some stuff
    return a+b;
  }
}
app.controller('myController',function(myFunctions){
  myFunctions.addNumbers(2,2); // 4
})
Community
  • 1
  • 1
David Boskovic
  • 1,469
  • 9
  • 14