有没有办法将变量传递给angularjs中的模板?

时间:2015-07-21 04:10:33

标签: javascript angularjs templates

我有一个角度js模板,我通过ng-repeat调用来创建按钮。

<script type="text/ng-template" id="button.angular.template">
    <div class="in-page-button" ng-if="button.mode == '' || button.mode == undefined"><< button.text >></div>
    <a class="in-page-button" href="<< button.targetURL >>" target="_blank" ng-if="button.mode == 'external'"><< button.text >></a>
    <a class="in-page-button" href="" ng-click="changePage(button.internalLink)" target="_blank" ng-if="button.mode == 'internal'"><< button.text >></a>
</script>

<!-- some other code -->
<div ng-repeat="(key, button) in buttons" ng-include="button.angular.temlate">
<!-- some other code -->

效果很好,但现在我想用模板创建一个按钮。假设该模型被称为singleButton。有没有办法将值传递给模板中的按钮变量?

P.S。好像我的问题不够明确。我希望在不更改模板代码的情况下使用模板。如果我可以将singleButton绑定到button,那么我可以直接重用模板。实际模板比3行长得多,因此如果我需要更改模板,则需要花费很多时间。

1 个答案:

答案 0 :(得分:1)

您可以将singleButton作为$ scope.button添加到您的范围。在ng-repeat中你的模板将使用循环变量'button',但除此之外它将使用$ scope.button。

这是一个显示此动作的傻瓜:

http://plnkr.co/edit/fkUQ9vm2AxO1m1Ul3g8t?p=preview

的index.html

<p>Start repeats</p>
<div ng-repeat="name in names" ng-include src="'template.html'"></div>
<p>End repeats</p>

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

app.js

app.controller('MainCtrl', function($scope) {
  $scope.names = ['Earth', 'Planet', 'Bote'];
  $scope.name = 'World';
});

template.html

<p>Hello {{name}}!</p>
相关问题