ReeMan
ReeMan

Reputation: 23

Why can't I pass $scope and $router in controller params?

(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.

Upvotes: 2

Views: 215

Answers (1)

Shomz
Shomz

Reputation: 37701

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();

Upvotes: 1

Related Questions