2016-08-02 52 views
0

我最近聲明學習角度js ..請幫助我.. 我想加載和編譯需求角度指令(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!"); 
}; 
} 
}; 
}); 

在這裏,我不加入index.html中的mydiv.js SRC .. 現在onclick按鈕它加載js文件,但不顯示..我需要修改我的代碼.. 謝謝..

回答

0

You sho uld必須包含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> 
+0

感謝您重播,其實我試圖按需加載指令,如果它包含在隨後的index.html文件mydev.js會只加載頁面加載,我試圖避免那一個.. –