Angularjs代码未在匿名函数中运行
Angularjs code not running in anonymous function
我编写了一个匿名javascript函数,它动态加载jQuery和Angular。然而,由于某种原因,我的角度代码没有运行。代码一直在find中工作,直到我达到main
函数。然后,我尝试发出http请求,并在我的角度控制器中打印结果,但由于某种原因,它们无法打印。。有人能帮忙吗?这是我的小提琴和代码:
https://jsfiddle.net/5f44yb7k/1/
提前感谢!
(function() {
var jQuery;
var jquery_tag = document.createElement('script');
var angular_tag = document.createElement('script');
function getJqueryTag() {
console.log('getting jquery tag');
jquery_tag.setAttribute("type","text/javascript");
jquery_tag.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js");
jquery_tag.onload = scriptLoadHandler;
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(jquery_tag);
if(jquery_tag.onload) { //ensure angular loads after jQuery
getAngularTag();
}
}
function getAngularTag() {
console.log('now getting angular tag...');
angular_tag.setAttribute("type","text/javascript");
angular_tag.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js");
angular_tag.onload = scriptLoadHandler;
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(angular_tag);
}
getJqueryTag();
function scriptLoadHandler() {
if(window.jQuery) {
jQuery = window.jQuery
main();
}
}
function main() {
jQuery(document).ready(function($) {
console.log('now in main function'); //this prints fine
var test = angular.module('test', []);
function main_controller($scope, $http) {
$http.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22fairfax%2C%20va%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys')
.success(function(data) {
console.log('---data returned---'); //not printing
console.log(data); //not printing
})
.error(function(data) {
console.log('error: ' + data);
});
}
});
}
})();
Angular正在脱离范围。如果以这种方式加载,则需要调用bootstrap函数来启动angular并运行它。
我从未以这种方式加载过它,但请参阅:https://docs.angularjs.org/guide/bootstrap,特别是关于手动初始化的部分。
相关文章:
- 关注函数运行过的表单字段(新手)
- 在函数运行时显示对话
- Javascript - 加载函数运行时未定义的变量
- Javascript变量在函数运行后不断重置自身
- 如何让 setTimeout 函数运行,然后停止使用循环
- 如何在函数运行之前隐藏 CSS
- 使用 .on 函数运行 jQuery 声明函数
- 在函数运行期间关闭 onClick
- jQuery停止函数运行两次
- Javascript:如何在函数运行完成之前对文档进行更改
- nodejs - 为什么我的异步函数运行两次
- 在传递值后停止函数运行
- 如何在 javascript 中的函数中将字符串作为函数运行
- 如何停止计时器函数运行
- 在浏览器空闲后保持设置超时函数运行
- JQuery:阻止一个函数运行,直到满足另一个函数条件“X”时间
- Angular 提供程序服务需要 init 函数运行一次
- 更新 Angular $interval 中的变量会导致其他函数运行
- 如何阻止此 setTimeout 函数运行
- 传入函数数组作为参数,对于函数中的每个函数运行函数