shiruken shiruken - 1 year ago 156
AngularJS Question

UI-Router's ui-sref creating wrong href

I have a SPA with 2 ui-views: header and body. The header is run by one controller, and the controllers that handle the body (depending on the state) make a call to a service function I created as follows:

* Sets the header bar's attributes
* @param inverse bool Whether the color scheme should be inverted
* @param button bool Whether the back button should be presented
* @param link string The route the back button will take the user to when pressed
* @param title string The translation key to use for the title to be shown in the headerbar
* @param data string Characters to be inserted in the span next to the title
return {
set: function(inverse, button, link, title, data) {
// set defaults
inverse = typeof inverse !== 'undefined' ? inverse : false;
button = typeof button !== 'undefined' ? button : false;
link = typeof link !== 'undefined' ? link : $;
title = typeof title !== 'undefined' ? title : undefined;
data = typeof data !== 'undefined' ? data : false;
// store for HeaderController to retrieve
$localStorage.headerInverse = inverse;
$localStorage.headerBackButton = button;
$localStorage.headerBackLink = link;
$localStorage.headerTitle = title;
$localStorage.headerData = data;


Like so:

header.set(true, true, 'app.search1', 'MY_PROFILE');

The header's controller listens to the broadcast with:

broadcast.listenFor('setHeader', function() {
vm.headerTitle = $localStorage.headerTitle; // expects the translation key to look up
vm.headerData = $localStorage.headerData;
vm.headerInverse = $localStorage.headerInverse;
vm.headerBackLink = $localStorage.headerBackLink;
vm.headerBackButton = $localStorage.headerBackButton;
vm.headerMoreIcon = $localStorage.headerMoreIcon;

And the header's html has:

<a ui-sref="{{ vm.headerBackLink }}"></a>

So what I would expect is:

<a href="#/search1" ui-sref="app.search1"></a>

Yet what I'm getting rendered is:

<a href="#/profile" ui-sref="app.search1"></a>

Any help would be appreciated. Thanks!

Answer Source

Instead of passing state name dynamically, try this:

$scope.getLinkUrl = function(){
  return $state.href('state-name', {someParam: $scope.someValue});

 <a ng-href="{{getLinkUrl()}}">Dynamic Link</a>

Ref: Dynamically set the value of ui-sref Angularjs

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download