rafaels88
rafaels88

Reputation: 839

Flask + AngularJS - Using url_for()

I am using AngularJS + Flask in my application, and I want to know the best way to "produce" an url, and don't write any hard code url for this. I have this situation:

*considering that I'm using [[ ]] instead of {{ }} for AngularJS.

<dd ng-repeat="item in myList">
    <span ng-click="doAction('{{ url_for('my_url', id="[[item.id]]") }}')">
      [[item.name]]
    </span>
</dd>

This is not going to work, because Jinja2 do the process url_for() before AngularJS, so "[[item.id]]" will not be substituted by AngularJS in time.

The problem is, I don't want to write in hard code like this:

<span ng-click="doAction('/my_url/[[item.id]]')">
    [[item.name]]
</span>

I am pretty new in AngularJS, maybe all my approach is wrong, so, does anyone have any idea what is the best way to make an element be clicked, make a request with an URL based on the context of the clicked element?

Upvotes: 4

Views: 1052

Answers (2)

Cole Murray
Cole Murray

Reputation: 593

In my case, I was trying to dynamically create urls

I solved my issue as follows (Note: I've swapped out Angular's syntax to {[x]}:

<ul>
    <li ng-repeat="x in projects">
        {[x.title]}
        {% set url = url_for('static',filename="img/") %}

        <img src="{{url}}{[x.img]}">
    </li>
</ul>

Upvotes: 1

dustinmm80
dustinmm80

Reputation: 972

I just ran across this problem. I ended up using Jinja2's {% set ... %}.

This is how I solved it, adapted for your example.

<dd ng-repeat="item in myList">
    {% set url = url_for('my_url', id="[[item.id]]") %}

    <span ng-click="doAction('{{ url }}')">
        [[item.name]]
    </span>
</dd>

Upvotes: 1

Related Questions