user1200387 user1200387 - 3 months ago 91
Javascript Question

Calling angularjs scope function from href

I am using a library which appends a href element onto an tag. On this link I need to make a call to an angularjs function that is within scope. Something like...

<a href="{{someFunction()}}"></a>

Note: I am attaching this href via javascript from another library (nvd3.js) not actually writing this in because if I was I could easily use ng-click or ng-href.


That's a bit convoluted.

CAVEAT: This is very, very hacky and just absolutely exactly what you're NOT supposed to do in angular, but I guess you know that and the library is making your life hard...

First, unlike onclick, an href won't interpret a string as javascript. Instead, you'd have to use

<a href="javascript:someFunction()"></a>

But this alone won't make it work, because someFunction() is not a method on the document, but on the controller, so we need to get the controller first:

<a href="javascript:angular.element(

Where myController refers to the DOM element that is decorated with ng-controller, e.g.

<div data-ng-controller="SomeController" id="myController"> ... </div>

If someFunction modifies the state of the view, you'll also need to use $scope.apply, i.e.

<a href="javascript:angular.element(document.getElementById('myController')).

Note that you don't need the {{ }} syntax, because you're calling javascript directly, you're not asking angular to modify your markup.