简体   繁体   中英

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. I think this is a question for Firebase.

Use 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).

Example: Without ng-if : http://jsfiddle.net/TheSharpieOne/daFhp/ Notice the two calls, one without the var/file name. 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.

ng-if prevents the bad call.

UPDATE
Newer versions of AngularJS (1.2.0-rc3+) will have problems when you have ng-if on the same element as ng-include . To fix this you can simply wrap your ng-include element in an element with 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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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