2
(function() {
    function AppController($router) {
        $router.config([
            {path: '/courses',component: 'courses'},
            {path: '/',component: 'welcome'}
        ]);
    }
    angular.module('MainApp', ['ngNewRouter'])
        .controller('MainController', ['$router', 'CourseRepository', AppController, '$scope', function($scope) {
            $scope.$on('clicked', function(e){
                $scope.tgState = !$scope.tgState;
            })
        }]);
})();

I am trying to connect new angular route in one controller with some function I wrote. It works if I will do it in 2 separate controllers, but somehow it doesn't when I'm trying to connect it in one controller.

ReeMan
  • 23
  • 3

1 Answers1

1

Apart from the confusing use of the same name (Are you trying to merge two functions? Is that what you mean by "connecting them"? You can't do that in JS, see below), you're instantiating it wrong. This:

.controller('AppController', 
            ['$router', 'CourseRepository', AppController, '$scope',
            function($scope) {

should be this:

.controller('AppController', 
            ['$router', 'CourseRepository', 'AppController', '$scope', 
            function($router, CourseRepository, AppController, $scope) {

If your controller function doesn't have the same number of arguments as the controller array itself (minus the function), it's always a dead giveaway something is wrong. Also, in this format, AppController needs to be declared as a service or a factory or a provider...

More info about controllers: https://docs.angularjs.org/guide/controller


However, if you're trying to merge two functions, that won't work, see this simple example:

function f() {
  alert('a');
}

function f() {
  alert('b');
}

// no, it won't alert "ab"
f();
Shomz
  • 37,421
  • 4
  • 57
  • 85
  • OK, I changed some names so it is not so confusing now(controller name to MainController). I just want to have just one controller - MainController. In your solution I got error "[ng:areq] Argument 'AppController' is not a function, got undefined". – ReeMan Jul 14 '15 at 09:56
  • I'm not entirely sure what you're trying to achieve, but you cannot pass in the function body as a variable name. – Shomz Jul 14 '15 at 09:57
  • I just got some problem with arguments passing. In my previous solution, I got 2 controllers(1 - MainController, 2 - AppController). MainController was rensponsible for $scope, and this function using $scope. AppController handled whole routing. Now I need to merge them somehow in one controller. But when I add "function($scope){...}" to controller arguments, it doesn't work anymore. – ReeMan Jul 14 '15 at 10:03
  • You can't do it like that, read the first part of my answer. You can create a routing service - they are singletons. – Shomz Jul 14 '15 at 10:06