使用工厂内部控制器

Use factory inside controller

本文关键字:控制器 内部 工厂      更新时间:2023-09-26

我目前很难理解AngularJs中的模块原理。

我有3个文件:

  • 应用程序
  • 控制器
  • 工厂

我想在我的控制器中使用工厂:

app.js:

angular.module('myApp', ['ngMaterial', 'ngMessages']);

controller.js:

angular.module('myApp').controller('MyController', function () {
    ...
}

factory.js:

angular.module('myApp').
    factory('test', function () {
        return 'Just a test';
    });

我的控制器怎么能从test-工厂知道?

您将其作为依赖项注入,就像对"ngMaterial"、"ngMessages"所做的那样

angular.module('myApp').controller('MyController', ['test',function (test) {
 ...
]};

附言一下,这和这样做是一样的,但当你混淆你的代码时就可以了

angular.module('myApp').controller('MyController',function (test) {...};

将您的工厂注入到您想要使用的任何地方。在这种情况下,您的控制器。

angular.module('myApp').controller('MyController', function ('test') {
    ...
}

此外,值得记住的是,如果您有多个模块,您可以将它们相互注入,并通过依赖注入在彼此中使用它们的服务。

您的代码非常好。你只需要将工厂注入你的控制器中。见下文

angular.module('myApp').controller('MyController', ['$scope','test',function ($scope, test) {
 // Do your stuff here with test
]};

依赖注入!

看看这里。

将工厂注入控制器。然后,您可以使用控制器的出厂服务。