简体   繁体   English

在 Angular 中是否有等价于“blah”+ 变量 +“blah”?

[英]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-ifhttp : //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-ifhttp : //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.

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