将依赖关系传递给模块angular

时间:2016-06-08 13:10:59

标签: javascript angularjs controller dependencies

所以我对角度有点新,但不是javascript。我正在使用其他人编写的应用程序并尝试在现有模块中创建新控制器。就依赖性而言,控制器几乎彼此相同。我的问题是如何将相同的依赖项传递给两个控制器?看起来你可以像这样传递它们:

`angular.module('ApertureForm', ['dialogs.main','dialogs.default-translations','ui.bootstrap'])`

当我为两个模块执行此操作时,控制器会因任何原因返回undefined。多数民众赞成在哪里卡住了。你如何传递上述代码中的依赖项?任何建议都会很棒。

4 个答案:

答案 0 :(得分:1)

angular.module('ApertureForm', ['dialogs.main','dialogs.default-translations','ui.bootstrap'])告诉AngularJS初始化一个名为ApertureForm的Angular模块,并加载其他Angular模块作为模块的依赖

要向控制器添加依赖项,请执行以下操作:

angular.module('ApertureForm').controller('ControllerName', function($scope, $location, $timeout) {...});

angular.module('ApertureForm') =获取名为ApertureForm的模块。

然后创建一个名为ControllerName的控制器。闭包是注入依赖项的地方。

为防止控制器的依赖关系在缩小时重命名,您可以执行以下操作:

angular
    .module('ApertureForm')
    .controller('ControllerName', ControllerName);


    ControllerName.$inject = ['$scope', '$location', '$timeout'];

    function ControllerName($scope, $location, $timeout) {...}

文档:https://docs.angularjs.org/guide/di

答案 1 :(得分:0)

angular.module('ApertureForm',[中列出要注入模块的模块。您为每个模块列出一次。如果您想在其中一个模块中创建控制器,那么您可以使用:

var myApp = angular.module('ApertureForm');

myApp.controller('GreetingController', ['$scope', function($scope) {
  $scope.greeting = 'Hola!';
}]);

$ scope here是控制器

的依赖项

您可以阅读更多相关信息here

答案 2 :(得分:0)

AngularJS ControllersDependency Injection

angular
    .module('ApertureForm', ['dialogs.main','dialogs.default-translations','ui.bootstrap'])
    .controller('FormController', ['$scope', '$http', function($scope, $http) { 
        // FormController code...
    }])
    .controller('WebinarController', ['$scope', '$http', function($scope, $http) {
        // WebinarController code...
    }]);

答案 3 :(得分:0)

感谢大家的帮助!所有这些对于学习角度结构以及如何正确使用框架非常有用。 @Yosvel Quintero能够解释模块的工作原理以及我收到错误的原因。当依赖关系被传递到模块而不是控制器时,它们可供所有控制器使用,因为它自己的模块现在知道依赖关系,这就是为什么我不断尝试再次传递错误的原因。希望回答这个问题的答案可以帮助有人学习角度。谢谢你们!