简体   繁体   English

Flask + AngularJS - 使用url_for()

[英]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. 我在我的应用程序中使用AngularJS + Flask,我想知道“生成”url的最佳方法,并且不为此编写任何硬代码URL。 I have this situation: 我有这种情况:

*considering that I'm using [[ ]] instead of {{ }} for AngularJS. *考虑到我对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. 这不起作用,因为Jinja2在AngularJS之前执行url_for()过程,因此“[[item.id]]”不会被AngularJS及时替换。

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? 我在AngularJS中很新,也许我所有的方法都是错误的,所以,有没有人知道点击元素的最佳方法是什么,根据点击元素的上下文使用URL发出请求?

I just ran across this problem. 我刚碰到这个问题。 I ended up using Jinja2's {% set ... %} . 我最终使用了Jinja2的{% 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>

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]}: 我解决了我的问题如下(注意:我已将Angular的语法换成{[x]}:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM