javascript - 你可以使用 Angular 依赖注入(inject)而不是 RequireJS 吗?

标签 javascript angularjs

我从 Angular 开始,如何将一个应用程序的所有代码分解成多个文件?我看了 60 多分钟的介绍,他们提到我可以在没有 requirejs 或任何其他框架的情况下做到这一点。

假设我有这样的东西,效果很好:

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

app.factory('ExampleFactory', function () {
   var factory = {};
   factory.something = function(){
   /*some code*/
   }
   return factory;
});


app.controller ('ExampleCtrl', function($scope, ExampleFactory){
   $scope.something = function(){
      ExampleFactory.something();
    };
});

app.config(function ($routeProvider) {
    $routeProvider
    .when('/',
    {
    controller: 'ExampleCtrl',
        templateUrl: 'views/ExampleView.html'
    })
    .otherwise({ redirectTo: '/' });
});

如果我想将它放在单独的文件中怎么办?像这样

文件一:

   angular.module('factoryOne', [])
   .factory('ExampleFactory', function () {
       var factory = {};
       factory.something = function(){
       /*some code*/
       }
       return factory;
   });

文件二:

  angular.module('controllerOne', ['factoryOne'])
  .controller ('ExampleCtrl', function($scope,ExampleFactory){
      $scope.something = function(){
      ExampleFactory.something();
      };
  });

文件三:

angular.module('routes', ['controllerOne'])
.config(function ($routeProvider) {
     $routeProvider
     .when('/',
     {
    controller: 'ExampleCtrl',
        templateUrl: 'views/ExampleView.html'
     })
    .otherwise({ redirectTo: '/' });
 });

文件四:

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

我试过了,还是不行。 我可以做这样的事情并在主视图中只为文件四添加一个脚本标签吗?还是每个文件必须有一个脚本标签? 感谢大家的帮助。

最佳答案

AngularJS 目前没有脚本加载器作为框架的一部分。为了加载依赖项,您需要使用第三方加载器,例如 RequireJS、script.js 等。

根据文档(http://docs.angularjs.org/guide/module#asynchronousloading):

Asynchronous Loading

Modules are a way of managing $injector configuration, and have nothing to do with loading of scripts into a VM. There are existing projects which deal with script loading, which may be used with Angular. Because modules do nothing at load time they can be loaded into the VM in any order and thus script loaders can take advantage of this property and parallelize the loading process.

...或者,正如@xanadont 解释的那样,您可以添加 <script>为每个文件在您的页面上添加标签。

关于javascript - 你可以使用 Angular 依赖注入(inject)而不是 RequireJS 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17409682/

相关文章:

javascript - Ionic 2 等待多个响应

javascript - 是否可以在 AngularJS 中模拟按键?

javascript - JavaScript 中函数的执行顺序

javascript - 当我使用其他方法时,jQuery 加载动画未隐藏在已加载页面上或显示延迟

javascript - 使用 AngularJS 在应用程序运行时加载内容时进行单元测试

javascript - AngularJS:捕获所有响应状态 500

angularjs - 如何以 Angular 读取nodejs流?

angularjs - Angular 删除服务?

javascript - 保持用户 session 事件的正确方法

javascript - ComboBox typeAhead 可以工作,但 valueField 在某些行为条件下为空