Reputation: 2297
I have a section of HTML which the user will be in control of, but I need to give certain elements an ng-click. I know the general structure of the html will be a ul with li's for each page, and ul's inside those li's with other li's for each sub-page. But this will be entirely controlled by the user and I can't touch the HTML directly.
Say someone has created:
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#blog">Blog</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
and I want to turn it into:
<ul>
<li><a ng-click="$event.preventDefault(); openPage($event.target)" href="#home">Home</a></li>
<li><a ng-click="$event.preventDefault(); openPage($event.target)" href="#about">About</a></li>
<li><a ng-click="$event.preventDefault(); openPage($event.target)" href="#blog">Blog</a></li>
<li><a ng-click="$event.preventDefault(); openPage($event.target)" href="#contact">Contact</a></li>
</ul>
How can I do this after the page has loaded and angular has already bootstrapped? I know that typically, the solution would be to create a directive for anchor tags that replaces them, but I need the text in the anchor tags to remain as whatever the user set, I need the href to remain the same, and I need it to ONLY affect the anchor tags within this section. It can't effect any anchor tags outside of the parent ul tag.
Simply put, is there anything similar to using jquery to add attributes?:
$('ul').find('a').attr('ng-click', '$event.preventDefault(); openPage($event.target)');
Upvotes: 0
Views: 66
Reputation: 19040
You might be interested by this post : How to think Angular with a jQuery background.
You usually don't want to override ng-click and stuff like that. It usually shows a design problem, and won't work out in most cases.
What you probably want here is a directive on, for example, class="menu-link"
:
angular.module('foomodule', [])
.directive('menuLink', {
restrict: 'C', // C for class
link: function (scope, element, attributes, parentController) {
element.on('click', function () {
scope.openPage(element.attr('href'));
return false;
});
}
});
Upvotes: 1
Reputation: 1775
Would this work? http://plnkr.co/edit/vxowNUAnbQSkuiHpNvYZ
Leaving the href attribute empty prevents the default in angular.
After the application has bootstrapped you can populate the "options" collection in your model at the same point in your application where you would run the jQuery in your example above.
Let me know what you think.
Upvotes: 1