如何在routeprovider中注入控制器

时间:2015-06-04 15:06:37

标签: javascript angularjs route-provider

我对angularJS很新,这是我建议的问题。

我有一个route.js文件,它只存储路由相关的东西。 看起来像这样。

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: '/' });
}]);

我有另一个文件ontology.js,其中包含所有控制器,其中一个控制器是axiomFormCtrl。

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

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

现在,如果我运行该程序,它会说axiomFormCtrl is undefined。我不知道如何解决依赖问题。

1 个答案:

答案 0 :(得分:3)

首先,请确保将脚本包含在HTML中的ontology.js

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

其次,您要在此处定义模块两次:

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

在这里:

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

因此,使用所有必需的模块定义一次。这可以在名为app.js的文件中完成(您还需要将其包含在HTML中):

app.js

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

然后在将使用ontology model的所有其他文件中,使用相同的语法,减去第二个参数(其他模块的数组):

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: '/' });
    }]);
})();

和ontology.js

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

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