[英]Is there an equivalent of “blah” + variable + “blah” in Angular?
This actually works:这实际上有效:
<div ng-include="'/partials/' + items.my_filename + '.html'"></div>
But even though it finds the file it still gives me an error:但即使它找到了文件,它仍然给我一个错误:
GET http://localhost:9000/partials/.html 404 (Not Found)
I'm glad it works but does anyone know how to get rid of the error?我很高兴它有效,但有人知道如何摆脱错误吗?
EDIT: it's pulling the variable from a remote database, could the delay be causing the error?编辑:它从远程数据库中提取变量,延迟会导致错误吗?
EDIT2: Yep, that's what's causing it. EDIT2:是的,这就是造成它的原因。 I think this is a question for Firebase.
我认为这是 Firebase 的问题。
Use ng-if
使用
ng-if
<div ng-if="items.my_filename" ng-include="'/partials/' + items.my_filename + '.html'"></div>
Example: With ng-if
: http://jsfiddle.net/TheSharpieOne/daFhp/1/ Notice only one call, with the file name (which would work if that file was there).示例:使用
ng-if
: http : //jsfiddle.net/TheSharpieOne/daFhp/1/注意只有一个调用,带有文件名(如果该文件在那里就可以工作)。
Example: Without ng-if
: http://jsfiddle.net/TheSharpieOne/daFhp/ Notice the two calls, one without the var/file name.示例:没有
ng-if
: http : //jsfiddle.net/TheSharpieOne/daFhp/注意两个调用,一个没有 var/file 名称。 One with the file name (which would work if that file was there).一个带有文件名(如果该文件在那里就可以工作)。
I am using $timeout
in the examples to simulate delay in AJAX calls.我在示例中使用
$timeout
来模拟 AJAX 调用中的延迟。
ng-if
prevents the bad call. ng-if
防止错误调用。
UPDATE更新
Newer versions of AngularJS (1.2.0-rc3+) will have problems when you have ng-if
on the same element as ng-include
.当您在与
ng-include
相同的元素上使用ng-if
时,较新版本的 AngularJS (1.2.0-rc3+) 会出现问题。 To fix this you can simply wrap your ng-include
element in an element with ng-if
.要解决此问题,您可以简单地将
ng-include
元素包装在一个带有ng-if
的元素中。
<div ng-if="items.my_filename">
<div ng-include="'/partials/' + items.my_filename + '.html'"></div>
</div>
Use the fact that ng-include
, given a null
argument, will just do nothing.使用一个事实,即
ng-include
,给定一个null
参数,什么都不做。
As a result you could go this way结果你可以走这条路
<div ng-include="partialPath"></div>
with, for instance例如
app.controller('Ctrl', function ($scope, $http) {
$scope.partialPath = null;
$http.get(...).success(function (data) {
$scope.partialPath = '/partials/' + data.my_filename + '.html';
});
});
Or you could also use a filter like this (very good for re-use)或者你也可以使用这样的过滤器(非常适合重复使用)
app.filter('partialize', function () {
return function (name) {
return name ? '/partials/' + name + '.html' : null;
};
});
with the following partial definition具有以下部分定义
<div ng-include="my_filename | partialize"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.