Angularjs 不会在 ng-view 中加载脚本 [英] Angularjs does not load scripts within ng-view
问题描述
我有一些特定于视图的脚本.但是,当 angularjs 加载视图时,脚本似乎没有执行.
I had some scripts specific to a view. However, the script does not seem to execute when angularjs loads the view.
Index.html
<html>
<body ng-app="adminApp">
<div ng-view=""></div>
<script src="bower_components/angular/angular.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
</body>
</html>
Main.html - 在 ng-view 下加载
Main.html - loads under ng-view
hello world
<script>
alert('Hello, John!')
</script>
在这个例子中,当页面加载时,我看到一个基本的 hello world 打印在网站上.但是,我没有收到任何说你好,约翰"的弹出窗口.
In this example, when the page load, I see a basic hello world printed on the website. However, I do not get any pop up saying "Hello, John".
知道为什么我无法加载特定于某个视图的脚本吗?
Any idea why I cannot load scripts specific to a certain view?
额外信息app.js
'use strict';
angular.module('adminApp', [])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
controllers/main.js
'use strict';
angular.module('adminApp')
.controller('MainCtrl', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
推荐答案
这就是 jqLite 的工作方式.如果您希望评估模板中的脚本,请在 AngularJS 之前包含 jQuery.如果包含 jQuery,将评估该脚本.尝试删除 jQuery,您会看到最初观察到的行为.
That's the way jqLite works. If you want scripts in templates to be evaluated, include jQuery before AngularJS. If jQuery is included, the script will be evaluated. Try removing jQuery, and you see the originally observed behavior.
更新:由于有人要求在评论中详细说明,这里是:
Updated: since some people asked for elaboration in the comments, here it is:
当路由匹配时,ngView
使用 jqLite 的(或 jQuery 的,如果加载)html()
方法来设置元素的内容(一个 ngView
声明于).换句话说,ngView.link()
做了这样的事情:
When a route is matched, ngView
uses jqLite's (or jQuery's, if loaded) html()
method to set the content of the element (the one ngView
is declared on). In other words, ngView.link()
does something like this:
$element.html(template)
所以它归结为 html()
在 jqLite 和 jQuery 中是如何实现的.jqLite 使用原生的 innerHTML
属性,它只设置内容但不评估脚本.另一方面,jQuery 解析出所有脚本标记并执行它们(通过构造脚本 DOM 元素并将其附加到页面).
So it boils down to how html()
is implemented in jqLite and jQuery. jqLite uses the native innerHTML
property, which only sets content but doesn't evaluate scripts. jQuery, on the other hand, parses out all script tags and executes them (by constructing and appending script DOM elements to the page).
这篇关于Angularjs 不会在 ng-view 中加载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!