如何定义ng-include指令中使用的变量

时间:2013-06-13 14:47:13

标签: angularjs

我尝试在某些地方使用我的company_address.html模板,但视路线而定 它是由一个不同的变量构建的。

模板:

Username: {{ user.company.name }}
Company: {{ user.company.company_name }}

$http服务加载数据。

在商品页面上,用户由offer.user定义,但在我的订单页面上, 它由order.user定义。我想为此目的使用相同的模板。

我还想提一下,$rootScope中有一个用户定义为应用程序 需要身份验证。

我试过了:

<any ng-include="'path/to/company_address.html'" onload="user=offer.user">用于优惠页面,与onload="user=order.user"类似,但这不起作用。我知道onload修改了paranet范围,而不是修改了ng-include指令创建的范围。

是否可以包含与ng-include中定义的某个对象相同的html片段?

2 个答案:

答案 0 :(得分:1)

不使用@ james-sharp提出的ng-hide属性hack,而是使用ng-init directive。这允许您初始化范围上的变量。例如:

<div ng-init="test1 = (data | orderBy:'name')"></div>

答案 1 :(得分:0)

ng-include引入的任何代码仍应继承父作用域,因此您应该能够执行以下操作:

<强> HTML

<any ng-controller="FooCtrl">
    <!-- Whatever html you want here -->
    <any ng-include="path/to/company_address.html"></any>
</any>

<强>控制器

FooCtrl = function($scope){
    $scope.user = $scope.offer.user // or $scope.order.user
}

然后,您可以在company_address模板中使用user变量。如果你真的想在HTML中定义用户变量那么你可以做一个非常hacky:

<any ng-include="'path/to/company_address.html'" ng-hide="user = offer.user">

(假设用户不是空的)