Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically constructed ui-sref attribute in ui-router

I am new to angular and especially ui-router.

Here is a link:

<a ui-sref="/topic/{{topic.id}}">SomeText</a>

The link is dynamically populated.

So when I try to access that state from my config like this:

 .state('topics/:topicId',{
        url:"",
        templateUrl: "",
        controller: ""
    })

I get this error message:

Error: Could not resolve '/topics/myTopic' from state 'topics'

In the above: myTopic is a variable name.

like image 601
user3283104 Avatar asked May 05 '14 15:05

user3283104


People also ask

What does ui-sref do?

A ui-sref is a directive, and behaves similar to an html href . Instead of referencing a url like an href , it references a state. The ui-sref directive automatically builds a href attribute for you ( <a href=...> </a> ) based on your state's url.

What is ui-sref active in Angularjs?

ui-sref-active can live on the same element as ui-sref / ui-state , or it can be on a parent element. If a ui-sref-active is a parent to more than one ui-sref / ui-state , it will apply the CSS class when any of the links are active.


Video Answer


2 Answers

You are almost there. Just the parameter must be part of the URL definition, not the name of the state:

.state('topics',{
    url: '/{id:[0-9]{1,8}}', // we can also add some constraint, like int id only
    templateUrl: "",
    controller: ""
 })

And how to call it (where currentItem.id would be injected dynamically as a part of some ng-repeat)

<a ui-sref="topics({id:currentItem.id})">SomeText</a>

Because ui-sref means: ui-sref='stateName({param: value, param: value}). More info here:

  • ui router, URL Parameters
  • ui-sref
like image 106
Radim Köhler Avatar answered Oct 09 '22 18:10

Radim Köhler


Try to use a simple name for state as 'topics' and use 'topics/:topicId' as url property. After that you can use ui-sref='topics({topicId: topic.id})'

like image 45
wilver Avatar answered Oct 09 '22 17:10

wilver