【问题标题】:Can an AngularJS controller link a scope variable in it to an HTML file, the variable then being referenced to render the HTML file?AngularJS 控制器能否将其中的范围变量链接到 HTML 文件,然后引用该变量来呈现 HTML 文件?
【发布时间】:2015-03-26 11:20:01
【问题描述】:

我看到的示例显示了呈现 HTML 文件的指令代替指令。或者控制器将 HTML sn-p 渲染为范围变量,直接写在单引号之间 - 比如

$scope.items = '<ol><li>an item></li> <li>another item</li></ol>' 

(这对我来说效果不佳,因为我的 HTML sn-p 中间还有其他单引号似乎会阻止 HTML sn-p 正确呈现。)

以下是我尝试过但不起作用的方法:

控制器代码:

innerapp.controller('ResourcesController', function($scope, $sce, $http) {

$scope.template = 'employeelists.html';
});

HTML 代码:

 <div ng-controller="ResourcesController">

      <div ng-bind-html-unsafe="template"></div>
    </div>

我的 app/assets/templates 文件夹中有“employeelists.html”。我正在使用带有 Rails 的 AngularJS,这个设置已经让我可以像这样调用文件:

div ng-include="'employeelists.html'"></div>

但我希望控制器而不是 ng-include 来呈现 HTML 文件。

基本上,我正在研究这样的功能,如果我在 HTML 页面上选择一个项目(在这个 AngularJS 控制器下),控制器中的一个函数会被调用,它用另一个更新范围变量(链接到模板文件)模板文件。

【问题讨论】:

  • 不结合两个答案,给出你想要的? $scope.template = 'employeelists.html';&lt;div ng-include="template"&gt;&lt;/div&gt;
  • 我不知道你是怎么做的。那么通过控制器更新模板变量,“ng-include”渲染的内容也会发生变化吗?太好了,我去看看。
  • klauskpm,根据 HTML 中的选择,您是否推荐使用指令或控制器在此处呈现变化的模板变量的方法?
  • klauskpm,你的方法对我有用(一个范围变量,它引用 'app/assets/templates' 中的 HTML 文件,并且 ng-include 调用该范围变量)。

标签: html angularjs templates controller render


【解决方案1】:

首先,请记住 DOM 操作应始终留给指令,而不是控制器。其次,我强烈建议您使用 ui-router 查看视图。这可以轻松完成您想要做的事情。这是一个简单的视图更改示例: https://angular-ui.github.io/ui-router/sample/#/

另外,有人已经找到了一种将代码输入到 ng-include 指令的方法,因此您可以对其进行更新: angular - update directive template on click

但是,请阅读上面的答案,他还建议您使用 $stateProvider(ui-routers 状态配置器),因为这将是您尝试做的更简单的方法。

希望对你有帮助

【讨论】:

  • 根本不适合我。我确实先尝试了ui-router。根据我发现似乎可靠的在线指南,我已经用 Rails 配置了带有“angular-rails-templates”之类的 ui-router:start.jcolemorrison.com/…
  • 我会查看您提供的资源。 ui-router 正在使用 Rails 做一些事情(就像它试图将 'url' 部分添加到浏览器 URL 的末尾),但只是不呈现包含在 templateURL 中的 HTML 模板文件(模板文件在 app/assets /templates 文件夹)。
  • 如果您刚开始,我建议在尝试连接所有内容之前,先尝试配置 ui-router,然后尝试从 url 单独访问每个文件。例如:使用以下配置: ... angular.module('ngModule').config(function($stateProvider) { $stateProvider.$state('myState', { url: '/my-state-url' , templateUrl: '[insert your file directory here]' } ); }) ... 我会尝试访问 localhost:8080/#/my-state-url 以查看它是否加载。我会尽力提供帮助,但我主要在 nodeJS 和 express 中开发。祝你好运!
  • 另外,如果你卡住了,试试这个,当我刚启动时,它对我有很大帮助,它是 ui-router 的快速入门指南:scotch.io/tutorials/angular-routing-using-ui-router
猜你喜欢
  • 2010-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多