Reputation: 497
I'm new to Angular and trying to figure out how to run JavaScript which is only specific to one template.
If I include the script in the main page, it doesn't work bevause the specifric DOM relevant to the template has not been loaded yet.
I've tried Event Delegation but that's not working.
Is there a way to include the script inside the controller so it runs after the template called has loaded?
This is my code:
.when("/user-form", {
templateUrl: "templates/form.html",
controller: "FormControl"})
app.controller('FormControl', function($scope) {
});
Upvotes: 2
Views: 1507
Reputation: 8381
Usually you need to declare directives (those are your independent (or semi-independent) template-blocks which have own encapsulated logic.
You need to register directives, and usually it is better done using DDO - Directive Definition Object (check snippet below)
1st there is link function, which is part of DDO (directive definition object) in angular, and happens once all DOM already been rendered.
app.directive('helloWorld', function() {
return {
restrict: 'AE',
templateUrl: 'templates/myTemplate.html',
controller: ControllerFunction,
link: function(scope, elem, attrs) {
// your link function code
}
};
});
There are plenty of guides about link function and it's place in the rendering cycle.
there are also ways to deal with async data binding within controller, and usually it creates better and more maintenable practice, as link function structure normally intends to be more dom-manipulative and jquery-like.
As i understand from your question you just need to read more material on angular directives, their templates, data binding, their DDO and DDO structure and it's standard properties and methods.
Good Luck!
Upvotes: 2