AngularJs -在js指令中链接js代码

AngularJs - Linking js code within js directive

本文关键字:js 链接 代码 指令 AngularJs      更新时间:2023-09-26

对于我正在构建的angularjs应用程序,我有一个非常详细的指令。我想打破代码分离JS文件,然后将它们包含到1 JS指令文件。例如,与其将所有代码放在一个js文件中,不如这样写:

myapp-directive-http-request.js
myapp-directive-init.js
myapp-directive-event.js
myapp-directive-function.js

然后myapp-directive.js会链接到上面所有的文件。

几乎我正在寻找一个类似的函数包括("FILEPATH")在PHP或作为ng-include在angularjs html视图。有可能在指令部分内做这个javascript或angularjs吗?

我的指令代码如下:

angular.module("myApp", [])
.directive("myApp",['$http', function($http){
return{
            link: function(scope,element,attrs){ // normal variables rather than actual $scope, that is the scope data is passed into scope
                //all functions, init etc code is here
            },//return
            restrict:"A", //assign as attribute only ie <div my-modal> Content </div>
            replace:true,//replaces div with element, note if this is the case must all template must be wrapped within one root element. eg button is within ul otherwise get an error. 

            templateUrl:"partials/myapp/myapp.html",//template
            transclude:true, //incorporate additional data within
            scope:{
            } //If on this should mean the html input is not binded to custom directive
        }//return
}])

使用您选择的任何构建系统。Webpack、RequireJS、Browserify、JSPM——它们都能做到这一点。require('...')函数(在JSPM的情况下是ES2015-fashioned System.import)将完成这项工作。

在这种情况下,不建议异步加载模块(而不是构建一个bundle),因为指令编译过程不会等待它们被加载。
myapp-directive-http-request.js
myapp-directive-init.js
myapp-directive-event.js
myapp-directive-function.js

看起来不像是一个好的分手。臃肿的指令或控制器通常是糟糕设计的标志。一般来说,你可能想要把所有与DOM或作用域无关的东西分开,并保持指令的完整。从一个指令生成多个指令也可能是有益的。