本文介绍了如何动态构建 ng-include src?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

<ng-include ng-init="bootstrapModule(module.Id)" src=""></ng-include>

我希望能够像这样在 src 中构建一个字符串:

/modules/{{module.Name}}/{{module.Name}}.tpl.html

但我总是遇到障碍.我尝试使用回调函数来构建它,

$scope.constructTemplateUrl = function(id) {返回 '​​/modules/' + id + '/' + id + '.tpl.html';}

但是这被调用了 &过&结束,它似乎不喜欢那样.我也试过像这样构建它:

ng-src="/modules/{{module.Id}}/{{module.Id}}.tpl.html"

但这也行不通.与其花几个小时在灌木丛中徘徊,我想知道是否还有其他人遇到过这样的事情并有任何想法?

此外,当我从 $resource 中获取模块时,我会使用 $q 异步返回它们,所以我似乎无法在控制器之前将其添加到模块中作为 $scope.modules 就等于一个 then 函数.

有什么想法吗?

解决方案

ngInclude |src 指令需要一个角度表达式,这意味着您可能应该编写

ng-src="'/modules/' + module.Id + '/tpl.html'"

来自http://docs.angularjs.org/api/ng.directive:ngInclude

ngInclude|src 字符串角度表达式计算为 URL.如果source 是一个字符串常量,请确保将它用引号括起来,例如src="'myPartialTemplate.html'".

如果你在模型中构造 url 而不是内联 HTML 可能会更好

<ng-include src="module.url"></ng-include>

I have the following code:

<div ng-repeat="module in modules" id="{{module.Id}}">
    <ng-include ng-init="bootstrapModule(module.Id)" src=""></ng-include>
</div>

I want to be able to build a string in src like so:

/modules/{{module.Name}}/{{module.Name}}.tpl.html

But I keep hitting roadblocks. I've tried to use a call back function to build it,

$scope.constructTemplateUrl = function(id) {
    return '/modules/' + id + '/' + id + '.tpl.html';
}

But this gets called over & over & over and it doesn't seem to like that. I've also tried to construct it like so:

ng-src="/modules/{{module.Id}}/{{module.Id}}.tpl.html"

But that isn't working either. Rather than spend hours beating around the bush, I wondered if anyone else has come up against something like this and has any ideas?

Also, when I grab the modules from $resource, I am returning them asynchronously with $q, so I can't seem to go through and add it into the modules before in the controller as $scope.modules just equals a then function at that point.

Any ideas?

解决方案

ngInclude | src directive requires an angular expression, which means you should probably write

ng-src="'/modules/' + module.Id + '/tpl.html'"

From http://docs.angularjs.org/api/ng.directive:ngInclude

It might be better if you construct the url in model instead of inline HTML

<div ng-repeat="module in modules" id="{{module.Id}}">
    <ng-include src="module.url"></ng-include>
</div>

这篇关于如何动态构建 ng-include src?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 04:56
查看更多