AngularJS Link Href as a Function
by John Josef
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<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>
JavaScript
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);
}
}
});