how to inject controller in routeprovider

2.3k views Asked by At

I am quite new to the angularJS, here is my suggested problem.

I have a route.js file which only stores route related stuff. looks like this.

var app = angular.module('ontology', ['ngRoute']);

app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/abduction', {
            templateUrl: '/partials/abduction.html',
            controller: 'axiomFormCtrl',
        })
        .when('/logicDifference', {
            templateUrl: '/partials/logicDifference.html',
            controller: 'axiomFormCtrl',
        })
    .otherwise({ redirectTo: '/' });
}]);

and I have another file ontology.js which has all the controller and one of the controller is axiomFormCtrl.

var app = angular.module('ontology', ['ngResource', 'ngRoute']);

app.controller('axiomFormCtrl', function ($scope, $http) {
    console.log("in axiom form ctrl....");
});

Now if I ran the program, it will say that axiomFormCtrl is undefined. I am not sure how I can resolve the dependency problem.

1

There are 1 answers

1
Tom On BEST ANSWER

First, make sure you are including the script to ontology.js in your HTML:

...
<script src="routes.js"></script>
<script src="ontology.js"></script>

Second, you are defining your module twice, here:

var app = angular.module('ontology', ['ngRoute']);

And here:

var app = angular.module('ontology', ['ngResource', 'ngRoute']);

So, define it one time, with all of the required modules. This might be done in a file called app.js (which you'll also need to include in your HTML):

app.js

(function() {
    var app = angular.module('ontology', ['ngResource', 'ngRoute']);
})();

And then in all of your other files that will use the ontology model, use the same syntax, minus the second parameter (the array of other modules):

routes.js

(function() {
    var app = angular.module('ontology');

    app.config(['$routeProvider', function ($routeProvider) {
        $routeProvider
            .when('/abduction', {
                templateUrl: '/partials/abduction.html',
                controller: 'axiomFormCtrl',
            })
            .when('/logicDifference', {
                templateUrl: '/partials/logicDifference.html',
                controller: 'axiomFormCtrl',
            })
        .otherwise({ redirectTo: '/' });
    }]);
})();

And ontology.js

(function () {
    var app = angular.module('ontology');

    app.controller('axiomFormCtrl', function ($scope, $http) {
        console.log("in axiom form ctrl....");
    });
})();