应用程序基础:为 angularjs 控制器、服务等创建单独的文件

Foundation for apps: Creating separate files for angularjs controllers, services etc

我刚开始使用 Foundation for Apps,但我在将我的 angular 控制器添加到单独的文件夹 并使用它们时遇到了问题。

我的 assets 的 js 文件夹中有这个当前结构:

js/
   app.js //this has all the controllers etc. by chaining

但我希望它是

js/
   app.js
   controllers/
       home.controller.js
       main.controller.js

我不想保留通过链接我的控制器、服务等开发的单个大型 js 文件。我想要一个更模块化的结构。

当我改成模块化结构时,出现以下三个错误:

1. 'HomeCtrl' not defined.
2. Uncaught SyntaxError: Unexpected token < at the 1st line of home.controller.js
3. Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8079/assets/js/home.controller.js". at the point where I am including 'home.controller.js' in index.html

这是我的模板:

---
name: home
url: /
controller: HomeCtrl
---

<div class="grid-container">
  <h1>Welcome to Foundation for Apps!</h1>
  <p class="lead">This is version <strong>1.1 Weisshorn</strong>.</p>
</div>

home.controller.js:

app.controller('HomeCtrl', ['$scope', function($scope) {
    $scope.temp = 'hello';
}]);

app.js:

var app = angular.module('application', [
  'ui.router',
  'ngAnimate',
  'foundation',
  'foundation.dynamicRouting',
  'foundation.dynamicRouting.animations'
])
  .config(config)
  .run(run)
;

config.$inject = ['$urlRouterProvider', '$locationProvider'];

function config($urlProvider, $locationProvider) {
  $urlProvider.otherwise('/');

  $locationProvider.html5Mode({
    enabled:false,
    requireBase: false
  });
}

function run() {
  FastClick.attach(document.body);
}

为了解决这个问题,我尝试通过引用 this

在 gulpfile.js 中添加我的控制器引用

我也提到了 this 但我仍然无法让它工作。知道我做错了什么吗?

里面 gulpfile.js 检查 this line。您会看到在耦合最小化文件时仅使用 client/assets/js/app.js。您还需要让它复制所有 controller.js 文件:

// These files are for your app's JavaScript
appJS: [
    'client/assets/js/app.js',
    './client/assets/js/controllers/*.js',
]

您还可以使用 angular 模块来保存所有控制器和服务,然后将其注入您的应用程序模块。这就是我使用它的方式 here and this is how it is also done in this great ready to use Fork : https://github.com/CreativityKills/foundation-apps-template

  • 注意:记得在每次修改配置文件后重启gulp,并检查你的代码是否已经很好地包含在构建的JS文件中(默认是/build/assets/js/app.js )