Calling angularjs scope function from href

user1200387 picture user1200387 · Jan 8, 2014 · Viewed 41.8k times · Source

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.

Answer

John Josef picture John Josef · Jul 1, 2014

So I was not pleased with the answer to this as it doesn't really utilize an elegant angular solution.

Here's my solution: http://jsfiddle.net/jjosef/XwZ93

HTML:

<body class="wrapper" ng-app="ExampleApp">
  <a my-href="buildUrl('one', aVariable, 'three')">This is my a tag with a function that builds the url</a>
</body>

JS:

angular.module('ExampleApp', []);
angular.module('ExampleApp').run(function($rootScope) {
  $rootScope.buildUrl = function() {
    var link = [];
    for(var i = 0; i < arguments.length; i++) {
      link.push(arguments[i].toLowerCase());
    }
    return '/#!/' + link.join('/');
  };

  $rootScope.aVariable = 'two';
});

angular.module('ExampleApp').directive('myHref', function($parse) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var url = $parse(attrs.myHref)(scope);
      element.attr('href', url);
    }
  }
});