我正在关注一个angular.js教程,其中一个控制器已经在IIEF中的单独文件中进行了decalred,以防止对全局范围进行控制。在该教程中使用了简单的vanilla javascript,但我选择使用ES6(并且还使用webpack作为捆绑器)。
这是最初的控制器代码是在没有ES6和webpack的情况下编写的(然后文件只是在html中的脚本标记中引用)
(function(){
"use strict";
angular.module("ngClassifieds")
.controller("classifiedsCtrl", ["$scope", function($scope){
$scope.name = "Ryann";
}]);
})();
这就是我用commonjs导出在其文件中编写控制器代码的方式,并且因为这个文件不会在html中简单引用,但是它的函数将使用commonjs require调用,我必须通过主app模块作为其功能的参数:
module.exports = (ngClassifieds => {
"use strict";
console.log('ngClassifieds : ' + ngClassifieds);
ngClassifieds.controller("classifiedsCtrl", $scope => {
$scope.name = "Ryann";
});
})(ngClassifieds);
这就是我从另一个文件中调用它的方式:
import angular from 'angular';
import classifiedsCtrl from './../components/classifieds.ctrl';
const ngClassifieds = angular.module('ngClassifieds', []);
classifiedsCtrl(ngClassifieds);
但是我在浏览器控制台中遇到了这一系列错误:
Uncaught ReferenceError: ngClassifieds is not defined
angular.js?3437:4640Uncaught Error: [$injector:modulerr] Failed to instantiate module ngClassifieds due to:
Error: [$injector:nomod] Module 'ngClassifieds' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.5.8/$injector/nomod?p0=ngClassifieds
at eval (eval at <anonymous> (http://localhost:3000/index.js:60:2), <anonymous>:68:12)
at eval (eval at <anonymous> (http://localhost:3000/index.js:60:2), <anonymous>:2082:17)
at ensure (eval at <anonymous> (http://localhost:3000/index.js:60:2), <anonymous>:2006:38)
at module (eval at <anonymous> (http://localhost:3000/index.js:60:2), <anonymous>:2080:14)
at eval (eval at <anonymous> (http://localhost:3000/index.js:60:2), <anonymous>:4617:22)
at forEach (eval at <anonymous> (http://localhost:3000/index.js:60:2), <anonymous>:321:20)
at loadModules (eval at <anonymous> (http://localhost:3000/index.js:60:2), <anonymous>:4601:5)
at createInjector (eval at <anonymous> (http://localhost:3000/index.js:60:2), <anonymous>:4523:19)
at doBootstrap (eval at <anonymous> (http://localhost:3000/index.js:60:2), <anonymous>:1758:20)
at bootstrap (eval at <anonymous> (http://localhost:3000/index.js:60:2), <anonymous>:1779:12)
http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=ngClassifieds&p1=Er…F%2Flocalhost%3A3000%2Findex.js%3A60%3A2)%2C%20%3Canonymous%3E%3A1779%3A12)
我不知道为什么在IIEF中传递变量并不成功,我也想知道使用IIEF本身是否值得。
答案 0 :(得分:1)
您想要导出常规功能,而不是使用IIFE:
module.exports = ngClassifieds => {
"use strict";
console.log('ngClassifieds : ' + ngClassifieds);
ngClassifieds.controller("classifiedsCtrl", $scope => {
$scope.name = "Ryann";
});
};