简体   繁体   中英

ES6 import syntax with Angular 1.5 UI Router

I'm trying to combine Angular 1.5, UI Router using ES6 import modules syntax with Babel & Webpack.

In my app.js I have:

'use strict';

import angular from 'angular';
import uiRouter from 'angular-ui-router';
...
import LoginCtrl from './login/login.ctrl.js'


const app = angular.module("app", [
        uiRouter,
        ...
    ])
    .config(function($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('login', {
                url: '/login',
                templateUrl: '...', 
                controller: LoginCtrl,
                controllerAs: 'login' 
            })
    });

In login/login.ctrl.js I have:

'use strict';

export default app.controller("LoginCtrl", function() {
    //code here
});

When I started my app I have following error message:

ReferenceError: app is not defined
 bundle.js:35422:2
Error: [$injector:modulerr] Failed to instantiate module app due to:
[$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it.

And second question. How can I use controller: "loginCtrl as login" syntax with ES6 import/export?

You are referring to 'app' variable inside your 'login/login.ctrl.js' but the variable is not defined (because you are importing the controller before defining it).

EDIT: Anyway each module has its own scope so you can't refer to variable from different module this way.

The solution I have in my mind is following:

  1. Inside 'login/login.ctrl.js' create new module

     'use strict'; import angular from 'angular'; angular.module('ctrlsModule', []) .controller('LoginCtrl', function () { }); 
  2. Add the module as dependence of your main 'app' module

     'use strict'; import angular from 'angular'; import uiRouter from 'angular-ui-router'; ... import './login/login.ctrl.js'; angular.module('app', [uiRouter, 'ctrlsModule', ...]) .config(function ($stateProvider, $urlRouterProvider) { $stateProvider .state('login', { url: '/login', templateUrl: '...', controller: 'LoginCtrl', controllerAs: 'login' }); }); 

I haven't tested the code but I believe you can see what I mean. Not sure what you mean with the second question but controllerAs in ES6 should work the same way as in ES5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM