cytsunny
cytsunny

Reputation: 5030

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.

<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. Is there a way to pass the value into button variable in template?

P.S. Seems like my question is not clear enough. 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. The actual template is much longer than 3 lines, so it would cost much time if I need to change the template.

Upvotes: 3

Views: 214

Answers (1)

shieldstroy
shieldstroy

Reputation: 1327

You can add singleButton to your scope as $scope.button. Inside the ng-repeat your template will use the loop variable 'button', but outside of that it will use $scope.button.

Here is 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>

Upvotes: 1

Related Questions