通过渲染字符串模板NG-包括 [英] Render string templates via ng-include

查看:133
本文介绍了通过渲染字符串模板NG-包括的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图渲染HTML的一部分,在一个动态路由可用,途径是通过 $ http.get()通话牵强,它会返回一张HTML中,

I am trying to render a piece of html, available on a dynamic route, the route is fetched via a $http.get() call, it returns a piece of html,

只给一个例子,我尝试加载这个网站的部分:

Just to give an example I try to load this html partial:

<h1>{{ pagetitle }}</h1>
this is a simple page example

我做了一个小的小提琴,嘲笑的问题,但对于简单,我离开了HTTP调用出来,刚添加的HTML在范围内的字符串。

I made a small fiddle, to mock the problem, but for the simplicity i left the http call out, and just added the html in a string on the scope.

控制器是:

function Ctrl($scope) {
    $scope.data = {
        view: "<h1>whaaaaa</h1>"        
    }; 
}

HTML页面是这样的:

The page html is this:

<div ng-app="">
  <div ng-controller="Ctrl">
    <div ng-include src="data.view"></div>
  </div>
</div>

问题是,它不添加字符串到HTML文件(NG-包括),但它使一个HTTP调用,以取得该字符串aparently的网址。

The problem is that it does not add the string into the html file (ng-include), but it makes a http call to a url made of that string aparently.

那么,这不可能只是输入一个字符串转换成包括哪些内容?如果没有,是什么使一个HTTP调用动态链接,并输入URL返回到页面的正确方法。

So Is it not possible to just enter a string into an include? if not, what is the proper way to make an http call to a dynamic url, and enter the returned url into the page.

您可以在的jsfiddle

推荐答案

您可以添加静态挂钩模板缓存,让我们说你有,获取模板的服务:

You can add static hooks to the template cache, so let's say you have a service that gets the template:

myApp.service('myTemplateService', ['$http', '$templateCache', function ($templateCache) {
  $http(/* ... */).then(function (result) {
    $templateCache.put('my-dynamic-template', result);
  });

  /* ... */
}]);

然后,你可以这样做:

Then, you can do:

<div include src=" 'my-dynamic-template' "></div>

注意引用名称必须被包裹在单引号,这总是字节我.... 注意

NOTE reference name must be wrapped in single quotes, this always bytes me.... NOTE

请注意,您必须有它分配给模板缓存前角尝试解析URL。

Do note that you'll have to have assigned it to the template cache before angular tries to resolve the url.

编辑:

如果动态URL的逻辑是很简单的,你也可以使用一个条件中的NG-包括例如

If the dynamic URL logic is simple enough, you can also use a conditional in the ng-include, e.g.

<div ng-include="isTrue() && 'template1.html' || 'template2.html'"

这篇关于通过渲染字符串模板NG-包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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