Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Angular template into multiple small templates

Tags:

angularjs

In my Angular app, I'm trying to understand what would be the right way to split my page into components.

The page before the change is similar to:

<div id='settings'>

  <p class='controlGroup' ng-controller="FirstCtrl">
    <label class='control-label'>First Control</label>

    <div class="control">
        <!-- some inputs -->
    </div>
  </p>

  <p class='controlGroup' ng-controller="SecondCtrl">
    <label class='control-label'>Second Control</label>

    <div class="control">
        <!-- some inputs -->
    </div>
  </p>

    </p>


  <button id='saveBtn' class='saveButton' ng-click='saveSettings()'>Save Changes</button>

</div>

Although the control logic is separated to two different controllers, I want to separate theirs template as well, so it would be easy to reuse them or to move them to a different location.

I see many options: ng-include, script tag etc.

What would be the right way to do that?

like image 839
Roy Tsabari Avatar asked May 06 '13 11:05

Roy Tsabari


1 Answers

Using ng-include you can have different templates and simply inject them into parts of your DOM using it, it's good for times when you want to load different views based on different situations like clicking a nav button or a variable or so, please note that ng-include also compiles the template so you can use controllers and other angular features and directives in the template, here is an example from angularjs docs:

here is your main html:

<!doctype html>
<html ng-app>
  <head>
    <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body>
    <div ng-controller="Ctrl">
      <select ng-model="template" ng-options="t.name for t in templates">
       <option value="">(blank)</option>
      </select>
      url of the template: <tt>{{template.url}}</tt>
      <hr/>
      <div ng-include src="template.url"></div>
    </div>
  </body>
</html>

and here is the js:

function Ctrl($scope) {
  $scope.templates =
    [ { name: 'template1.html', url: 'template1.html'}
    , { name: 'template2.html', url: 'template2.html'} ];
  $scope.template = $scope.templates[0];
}
like image 125
Amir Avatar answered Oct 26 '22 17:10

Amir