我是Angular的新手,但我搜索了好几个小时,似乎无法弄清楚我做错了什么......我试图解决的问题是能够执行一些jQuery后部分已经加载。我发现这篇文章:http://blog.ruedaminute.com/2012/02/angular-js-applying-jquery-to-a-loaded-partial/,它解释了如何使用ng:include代替ng:view,但它不起作用 - 模板没有被包含,更不用说正在执行的onload。Angular:ng:包含当前模板和范围?
的index.html:
<!DOCTYPE html>
<html ng-app="shorelinerealtors">
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="/lib/angular.js"></script>
<script src="/lib/angular-resource.js"></script>
<script src="/js/app.js"></script>
<script src="/js/controllers.js"></script>
<link rel="stylesheet" href="/css/style.css">
<title>Shoreline Realtors</title>
</head>
<body>
<!--It works fine using ng:view, but of course no onload option-->
<!-- <ng:view></ng:view> -->
<!--This apparently does nothing... no hello world, no alert -->
<ng:include src="$service('$route').current.template" scope="$service('$route').current.scope" onload="init()"></ng:include>
</body>
</html>
residential.html
<h2>{{hello}}</h2>
controllers.js
function ResidentialListCtrl($scope) {
$scope.hello = "Hello World!";
this.init = function() {
alert("hello");
};
}
app.js
angular.module('shorelinerealtors', ['listingsServices']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/listings/residential', {templateUrl: '/partials/residential.html', controller: ResidentialListCtrl}).
otherwise({redirectTo: '/listings/residential'});
}]);
更新: 我为此创建了一个jsfiddle:http://jsfiddle.net/xSyZX/7/。它适用于ngView,但不适用于ngInclude。我是否需要在全局范围内定义$ service?
你能告诉你的代码,它定义了'NG-include'指令范围'$ service'? – Tosh
嗯......也许这就是我想念的东西?我没有在任何地方定义$ service。你能举一个我怎么做的例子吗? – corinnaerin
我设法让它与一些迂回解决方案一起工作:http://jsfiddle.net/xSyZX/11/。但是,我并没有意识到在部分评估之前onload会执行,所以它仍然不会按照我的意愿去做。我曾经和我一起工作过的人谈过,他建议把它封装到一个jQuery插件中,并使用angularui的jQuery Passthrough或者为它创建一个自定义指令。 – corinnaerin