2

I want to pass a variable or text through to a template so that it shows the value inside my template.

I come across jsFiddle which shows it working but it uses ng-repeat. Is there a simplere way to do this without using ng-repeat?

<div ng-repeat="name in ['John']" ng-include="'partial.html'"></div>
<div ng-repeat="name in ['Jack']" ng-include="'partial.html'"></div>

<script type="text/ng-template" id="partial.html">
   <div>The name is {{ name }}</div>
</script>
2
  • Using just one div?? <div ng-repeat="name in ['John','Jack']" ng-include="'partial.html'"></div> Commented Nov 19, 2014 at 17:19
  • The above divs would be split to other parts of a page so no need for ng-repeat Commented Nov 19, 2014 at 17:20

1 Answer 1

7

http://jsfiddle.net/f97keutL/

<div ng-controller="ctrl">
   <div ng-include="'partial.html'"></div>
</div>
<script type="text/ng-template" id="partial.html">
   <div>The name is {{ name }}</div>
</script>

JS:

var myApp = angular.module('myApp',[]);

myApp.controller('ctrl', function($scope) {
    $scope.name = "John"; 
});

You just set the variable in the scope, and include the template?

Sign up to request clarification or add additional context in comments.

5 Comments

I come across <div ng-init="name= 'John'" ng-include="'partial.html'"></div> Which seems to work. Could I get a second opinion?
Second opinion: Using ng-init is rather discouraged. It is encouraged to use controllers to do this initialization. The reason being a simple separation of concern between how and where a model should be initialized. And controllers have primary job of making the model available to the view. Views should not manipulate or even initialize any models.
You could do ng-init, but in my experience it's rare to use it, depends entirely on use case though. In general the html should describe what to show (i.e. show the users name), and your model (the javascript) would contain the value (what the users name is). Using ng-init puts the value in the view, which I would generally advise against.
@dave So I have a controller like this (let's say $scope is s for brevity): s.gridOne; s.gridTwo; s.notAGrid; and I want to create a template to show just the grids. How could I send just the grids? I can't do ng-repeat = "grid in s" because one of the elements are not a grid.
@Travis s.grids = [s.gridOne, s.gridTwo], ng-repeat = "grid in s.grids"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.