我正在遵循 angular.js 教程,其中 Controller 已被贴在 IIEF 内的单独文件中,以防止污染全局范围。该教程中使用了简单的普通 javascript,但我选择使用 ES6(并且还使用 webpack 作为 bundler )。
这就是最初在没有 ES6 和 webpack 的情况下编写 Controller 代码的方式(然后简单地在 html 中的脚本标记中引用该文件)
(function(){
"use strict";
angular.module("ngClassifieds")
.controller("classifiedsCtrl", ["$scope", function($scope){
$scope.name = "Ryann";
}]);
})();
这就是我使用 commonjs 导出在其文件中编写 Controller 代码的方式,并且该文件不会简单地在 html 中引用,但其函数将使用 commonjs require 调用,并且我必须传递主应用程序模块作为其函数的参数:
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 本身是否仍然值得。
最佳答案
您想要导出常规函数,而不是使用 IIFE:
module.exports = ngClassifieds => {
"use strict";
console.log('ngClassifieds : ' + ngClassifieds);
ngClassifieds.controller("classifiedsCtrl", $scope => {
$scope.name = "Ryann";
});
};
关于javascript - 无法在 IIEF 中传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39590599/