我正在关注angular.js教程,该教程中的控制器已在IIEF中的单独文件中进行了贴花处理,以防止破坏全局范围。在该教程中使用了简单的普通javascript,但我选择使用ES6(也将webpack用作捆绑程序)。
这是最初在没有ES6和webpack的情况下编写控制器代码的方式(然后仅在html的脚本标签中引用了该文件)
(function(){
"use strict";
angular.module("ngClassifieds")
.controller("classifiedsCtrl", ["$scope", function($scope){
$scope.name = "Ryann";
}]);
})();
这就是我如何通过commonjs导出在其文件中写入控制器代码的方式,也因为不会在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";
});
};