定义myApp并在服务中的控制器中重用它

时间:2015-12-11 11:56:55

标签: angularjs

我收到javascript运行时错误

  

myApp未定义

我的角度服务。不知道我在这做什么错..

这就是我定义app.js

的方式

app.js

var myApp = angular.module('myApp', [
    'ngRoute', 'motorControllers', 'motorDetailsController', 'motorServices', 'ngSanitize', 'ui.select', 'ngResource',]);

myApp.config(['$routeProvider',
  function ($routeProvider) {
      $routeProvider.
        when('/motors', {
            templateUrl: 'View/motorList.html',
            controller: 'motorController'
        }).
        when('/motors/:Id', {
            templateUrl: 'View/motorDetails.html',
            controller: 'motorDetailsController'
        }).
        otherwise({
            redirectTo: '/motors'
        });
  }]);

这就是我在控制器中创建/调用myApp的方式。

控制器

angular.module('myApp', []).controller('motorController', function ($scope, motorService) {

 //////
}

这就是我尝试在我的服务中使用myApp的方法。但它给出了错误myApp is undefined.

服务

myApp.service('motorService', ['$http', function ($http) {
//////
}

这就是我在html中声明的方式

<html ng-app="myApp">

期待一些帮助。 感谢

3 个答案:

答案 0 :(得分:1)

我认为错误发生在控制器的声明中,因为你要定义应用程序'myApp'两次。

angular.module('myApp', []).controller('motorController', function ($scope, motorService) {

 //////
}

应该是

angular.module('myApp').controller('motorController', function ($scope, motorService) {

 //////
}

编辑 @simbada

这取决于你。您可以将它们分成不同的模块。

(function(angular){
        angular
            .module('myApp', ['myApp.Controllers']);

        angular
            .module('myApp.Services', [])
            .service('mySrv', function($http){
                function _get(){
                    return $http.get('url');
                }

                return {
                    get: _get
                }
            });

        angular
            .module('myApp.Controllers', ['myApp.Services'])
            .controller('myCtrl', function($scope, mySrv){
                $scope.var = 'Hello';
            });
    })(angular);

答案 1 :(得分:0)

我认为这应该是

angular.module('myApp').controller('motorController', function ($sc...

whitout []括号。

还了解您如何申报服务:

var myApp = angular.module('myApp', [
'ngRoute', 'motorControllers', 'motorDetailsController', 'motorServices', 'ngSanitize', 'ui.select', 'ngResource']);

当您的服务是&#39; motorService&#39;

您的服务应该是:

myApp = angular.module('motorServices');
myApp.service('motorService', ['$http', function ($http) {

////// }

答案 2 :(得分:0)

ngResource之后,您已经通过了依赖性逗号,只是删除它才能正常工作。

var myApp = angular.module('myApp', [
    'ngRoute', 'motorControllers', 'motorDetailsController', 'motorServices', 'ngSanitize', 'ui.select', 'ngResource']);
相关问题