简体   繁体   English

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

[英]Is there a way to pass the variable to template in angularjs?

I have a angular js template that I called through ng-repeat to create buttons. 我有一个角度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 -->

It works well, but now I want to use the template to create a single button too. 它运作良好,但现在我也想使用模板创建一个按钮。 Let's say the model is called singleButton. 假设该模型被称为singleButton。 Is there a way to pass the value into button variable in template? 有没有办法将值传递给模板中的按钮变量?

PS Seems like my question is not clear enough. PS似乎我的问题不够明确。 I hope to use the template without changing the template code. 我希望在不更改模板代码的情况下使用模板。 It would be great if I can bind singleButton to button so I can directly reuse the template. 如果我可以将singleButton绑定到button ,那将是很好的,所以我可以直接重用模板。 The actual template is much longer than 3 lines, so it would cost much time if I need to change the template. 实际模板比3行长得多,因此如果我需要更改模板,则需要花费很多时间。

You can add singleButton to your scope as $scope.button. 您可以将singleButton作为$ scope.button添加到作用域。 Inside the ng-repeat your template will use the loop variable 'button', but outside of that it will use $scope.button. 在ng-repeat中你的模板将使用循环变量'button',但除此之外它将使用$ scope.button。

Here is a plunkr showing this in action: 这是一个显示此操作的plunkr:

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

index.html 的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.js

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

template.html template.html

<p>Hello {{name}}!</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM