【问题标题】:How to pass string argument to template using Angular如何使用Angular将字符串参数传递给模板
【发布时间】:2015-04-28 19:26:48
【问题描述】:

对于以下模板:

<h2 class="viewTitle">{{viewTitle | translate}}</h2>

我有时传递一个可翻译的字符串,有时传递一个范围内的变量。如果我包含这样的模板:

<div ng-init="viewTitle = 'translatable.title'" ng-include="'views/templates/view-title.html'"/>

一切正常。但是,我不能从我的范围传递变量。如何实现两者?

【问题讨论】:

  • 您的控制器范围是否与模板有效?您的控制器是否与模板关联?
  • 如果您从控制器执行此操作,则需要将模板 html 更改为 &lt;h2 class="viewTitle"&gt;{{$parent.viewTitle | translate}}&lt;/h2&gt;,因为 ng-include 确实创建了一个子范围

标签: html angularjs templates


【解决方案1】:

你的主要问题是:

How to set scope property with ng-init?。 在 Angular 有时间编写它之前,您正在使用 ng-init 读取范围属性。您不能在 ng-init 中访问 $scope 属性。而是在控制器中设置 $scope 属性(js 代码)。

这些是您可能会遇到的其他问题:

这会起作用(见下文),但您可能会遇到典型的角度范围问题,有两种可能的解决方案:

始终遵循点规则 (https://egghead.io/lessons/angularjs-the-dot),这将帮助您避免我们职业生涯中的许多范围界定问题

或使用“控制器作为”语法 (http://toddmotto.com/digging-into-angulars-controller-as-syntax/)。

模板:

<h2 class="viewTitle">{{myScopeAttributeInParentScope | translate}}</h2> data: {{myScopeAttributeInParentScope}}  

与字符串一起使用:

<div ng-init="myScopeAttributeInParentScope=translatable.title'}" ng-include="'views/templates/view-title.html'"/>

使用范围属性:

<div ng-include="'views/templates/view-title.html'"/>  
parent Scope: {{myScopeAttributeInParentScope}} 

【讨论】:

  • 感谢您的回答,特别是链接。但是,范围属性仍然不起作用。它是否试图在翻译文件中找到具有给定属性名称的条目?
  • 只需添加一些调试代码,这将使您的生活更轻松(参见上面的编辑答案)。另见这篇文章,它很好地解释了范围问题:stackoverflow.com/a/14146317/2766511
  • 确实,我猜它们都是空的,因为输出是data: data.viewTitle:
  • 实际上添加了您发给我的帖子中提到的 $parent hack,我可以显示可翻译的字符串。属性的调试(带有 $parent)是 data: {} data.viewTitle:
  • 也在你的父模板中添加调试代码,这样你才能看到完整的真相。我希望当时执行您的 ng-init 时, $scope.myScopeAttributeInParentScope 仍然是空的,因此它不起作用。将您的 ng-init 代码移动到 controller.js。
猜你喜欢
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 2021-02-24
  • 2017-05-31
  • 2011-06-29
  • 2010-09-14
相关资源
最近更新 更多