4

I'd like to bind a links href property to a variable in my controller but I'd also like to have that url be bound to variables. I'd like to accomplish this using the built in binding and without having to manually watch for changes and reload the url. Is this possible?

// In the controller
$scope.section = 'section1';
$scope.page = 'page1';
$scope.url = 'http://myurl/{{section}}/{{page}}';


<!-- In the template -->
<a ng-href="{{url}}">Page Link</a>

This is a simplification of my actual code. Declaring the url pattern in the template would work but I need to have the url be defined in a string that gets passed in.

Robert Johnstone
  • 5,431
  • 12
  • 58
  • 88
Stephen Marsh
  • 95
  • 1
  • 1
  • 7

2 Answers2

7

Just set the ng-href

<a ng-href="http://myurl/{{section}}/{{page}}">Page Link</a>
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Unfortunately this isn't an option. I need to hold the url in a string variable and can't have it declared in the template. The url is actually coming from a service that returns an array of urls. – Stephen Marsh Jan 22 '15 at 19:40
  • 1
    @StephenMarsh -- Looks like you'll probably need watchers then. – tymeJV Jan 22 '15 at 19:41
2

In the controller, you don't need to use curly braces expressions.

Replace this:

$scope.url = 'http://myurl/{{section}}/{{page}}';

With this:

$scope.url = 'http://myurl/'+$scope.section+'/'+$scope.page;

And to bind it in your template, use:

<a ng-href="http://myurl/{{section}}/{{page}}">Page Link</a>

So, you can now watch for any changes.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231