AngularJS:ngInclude 和动态 URL [英] AngularJS: ngInclude and dynamic URLs

查看:26
本文介绍了AngularJS:ngInclude 和动态 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ngInclude 指令来加载 HTML 片段.现在我正在寻找传递动态 URL 的最佳方式.我知道我可以用字符串连接创建 URL:

</ng-include>

在我看来这有点丑.

例如,

ngHrefngSrc 接受包含 {{}} 标记的 URL.恕我直言,这种语法要干净得多:

<img ng-src="/foo/{{fooId}}/bar/{{barId}}/baz/{{bazId}}"/><a ng-href="/foo/{{fooId}}/bar/{{barId}}/baz/{{bazId}}"/>

是否有更好的方法将动态 URL 传递给 ngInclude?

解决方案

不确定这是否更好",但您可以在作用域上创建一个函数来封装它.

app.controller("MyCtrl", function($scope) {$scope.fooId = "123";$scope.barId = "abc";$scope.bazId = "abc";$scope.templateUrl = function() {返回 "/foo/"+ $scope.fooId +"/bar/"+ $scope.barId +"/baz/"+ $scope.bazId;}});

然后你会像这样使用它...

<ng-include src="templateUrl()"></ng-include>

这是这类事情的一个活生生的例子:http://plnkr.co/edit/Lu3icqPgg1dpNCj6a3Dn?p=preview

I'm using the ngInclude directive to load HTML fragments. Now I'm looking for the best way to pass a dynamic URL. I know I can create the URL with string concatenation:

<ng-include src="'/foo/' + fooId + '/bar/' + barId + '/baz/' + bazId"></ng-include>

In my eyes this is a bit ugly.

ngHref and ngSrc for example, accept URLs containing {{}} markup. IMHO this syntax is much cleaner:

<img ng-src="/foo/{{fooId}}/bar/{{barId}}/baz/{{bazId}}"/>
<a ng-href="/foo/{{fooId}}/bar/{{barId}}/baz/{{bazId}}"/>

Is there a better way to pass dynamic URLs to ngInclude?

解决方案

Not sure if this is "better" or not, but you could create a function on your scope to encapsulate this.

app.controller("MyCtrl", function($scope) {
  $scope.fooId = "123";
  $scope.barId = "abc";
  $scope.bazId = "abc";

  $scope.templateUrl = function() {
    return "/foo/"+ $scope.fooId +"/bar/"+ $scope.barId +"/baz/"+ $scope.bazId;
  }
});

Then you would use it like so...

<div ng-controller="MyCtrl">
  <ng-include src="templateUrl()"></ng-include>
</div>

Here's a live example of this type of thing: http://plnkr.co/edit/Lu3icqPgg1dpNCj6a3Dn?p=preview

这篇关于AngularJS:ngInclude 和动态 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆