简体   繁体   English

按需加载和编译角度指令

[英]load and compile angular directive on demand

I'm recently stated learning angular js..Please help me out.. I'm trying to load and compile angular directive on demand(onclick)..I'm able to load the directive file(mydiv.js) but the mydiv.js file is not compiling.. Here is my code.. 我最近说要学习angular js ..请帮帮我..我正在尝试按需加载和编译angular指令(onclick)..我能够加载指令文件(mydiv.js)但mydiv .js文件未编译..这是我的代码..

index.html

<html>
<head>
<script src="jquery.min.js"></script>
<script src="angular.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>

<body>
<div ng-app="app">
<button type="button" onclick="disply_directive()">Click</button>
<my-directive ng-init="init()"></my-directive>
</div>
</body>
</html>

app.js

var app = angular.module('app', []);

var disply_directive = function () {
 load_scripts('mydiv.js');
}

var load_scripts = function(url) {
if (url) {
var script = document.querySelector("script[src*='"+url+"']");
if (!script) {
var heads = document.getElementsByTagName("head");
if (heads && heads.length) {
var head = heads[0];
if (head) {
script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', 'text/javascript');
head.appendChild(script);
}}}
return script;
}};

mydiv.js

app.directive('myDirective', function ($http) {
return {
template: '<h1>Hello World!</h1>',
strict: 'E',
link: function(scope) {
},
controller: function($scope) { 
$scope.init = function() {
alert("Hello World!");
console.log("Hello World!");
};
}
};
});

Here i'm not adding the mydiv.js src in index.html.. Now onclick of the button it loads the js file but not displaying..Where i need to modify my code.. Thank you.. 在这里,我没有在index.html中添加mydiv.js src。现在单击按钮的onclick会加载js文件,但不会显示。我需要修改代码的位置。。谢谢。

You should have to include the mydiv.js file with the index.html file rather than by calling onCLick(). 您必须将mydiv.js文件包含在index.html文件中,而不是通过调用onCLick()来进行。

<html>
<head>
<script src="jquery.min.js"></script>
<script src="angular.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="path_to_file/mydivjs"></script>
</head>

<body>
<div ng-app="app">
<button type="button" onclick="disply_directive()">Click</button>
<my-directive ng-init="init()"></my-directive>
</div>
</body>
</html>

I got the solution by using oclazyload - Load modules on demand (lazy load), here is my plunker ! 我通过使用oclazyload获得了解决方案-按需加载模块(延迟加载), here is my 功夫

reference : https://oclazyload.readme.io/docs 参考: https : //oclazyload.readme.io/docs

Thank you... 谢谢...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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