我是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