Reputation: 416
I'm new to Angular, but I've googled for hours and can't seem to figure out what I'm doing wrong... The problem I'm trying to solve is the ability to execute some jQuery after a partial has already loaded. I found this post: http://blog.ruedaminute.com/2012/02/angular-js-applying-jquery-to-a-loaded-partial/, which explains how to use ng:include instead of ng:view, but it doesn't work - the template isn't getting included, much less the onload being executed.
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'});
}]);
UPDATE: I created a jsfiddle: http://jsfiddle.net/xSyZX/7/ for this. It works with ngView but not with ngInclude. Do I need to do something to define $service in the global scope?
Upvotes: 2
Views: 2539
Reputation: 108481
If you want to use JQuery to effect elements on the page as they're loaded/handled, the "angular way" to do that would be to create a custom directive that did the jQuery work for you. Controllers are not supposed to be doing DOM manipulation, and that onload functionality is really for "business" logic set up for that include.
Here is an example of a directive that applies some JQuery to some element as soon as it's processed:
app.directive('moveRightOnClick', function() {
return {
restrict: 'A',
link: function(scope, elem, attr, ctrl) {
//elem is a jquery object if JQuery is present.
elem.click(function() {
$(this).animate({ 'left': '+=20' }, 500);
});
}
};
});
And here's how you'd use it.
<div move-right-on-click>Click Me</div>
If that is in your include's html, the jquery stuff will get wired up automatically by the directive.
Upvotes: 2