Is there a way to pass a variable to a template in angularjs?
I have an angular js template that I have called through ng-repeat
to create buttons.
<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 -->
This works well, but now I want to use a template to create one button. Let's say the model is named singleButton. Is there a way to pass a value in a button variable in a template?
PS It looks like my question is not clear enough. I hope to use the template without changing the template code. It would be great if I could bind singleButton
to button
so that I can use the template directly. The actual template is much longer than three lines, so it will take a long time to change the template.
source to share
You can add singleButton to your scope as $ scope.button. Inside the ng-repeat, your template will use the 'button' loop variable, but outside of it, $ scope.button will be used.
Here's a plunkr showing this in action:
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>
source to share