如何使用Angular将字符串参数传递给模板

时间:2015-04-28 19:26:49

标签: html angularjs templates

对于以下模板:

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

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

<div ng-init="viewTitle = 'translatable.title'" ng-include="'views/templates/view-title.html'"/>
事情很有效。但是,我无法从我的范围传递变量。如何完成两者?

1 个答案:

答案 0 :(得分:1)

你的主要问题是:

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

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

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

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

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

模板:

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

使用String:

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

使用范围属性:

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