I am still getting acquainted with angularjs, so there might be something I'm overlooking, but I'm struggling to find an efficient way to create reusable views that can be instantiated within a parent view.
My specific scenario involves a web application where the main view page contains several sub-panels that display similar content based on the same control and view template, but with varying configuration options. For example, small panels displaying summaries of stackoverflow questions, each configured to retrieve details for a different question ID.
You can access my JSFiddle demo here: http://jsfiddle.net/abierbaum/Agbdz/
I would appreciate feedback on two aspects:
- The best approach to passing initialization parameters to the sub-panel controllers.
- If there is a more optimal way to achieve this functionality.
Below is the key part of the code:
<!DOCTYPE html>
<div ng-app="app">
<div ng-init="names=['Jim','Spock','Jean Luc', 'Data', 'Riker']">
<h1>Non-looping instances</h1>
<br/><h1>First One</h1>
<div ng-include="'panel.tpl.html'"
ng-init="name = 'Bob'"
></div>
<br/><h1>Second One</h1>
<!-- Is this the best/only way to pass parameter to sub-panel? -->
<div ng-include="'panel.tpl.html'"
ng-init="name = 'Pete'"
></div>
<h1>Looping Forms</h1>
<!-- This is going to create a bunch of extra scopes: repeat & include -->
<div ng-repeat="name in names">
<div ng-include="'panel.tpl.html'"/>
</div>
</div>
<script type="text/ng-template" id="panel.tpl.html">
<div class="panel" ng-controller='PanelCtrl as ctrl'>
<br/>
<input type='text' ng-model='ctrl.name' />
<p>Current: {{ctrl.name}}</p>
<button ng-click="ctrl.sayHi()">speak</button>
</div>
</script>
</div>
And here's how the controller file is structured:
angular.module('app', [])
.controller('PanelCtrl', function($scope) {
this.name = $scope.name || 'Jack';
this.sayHi = function() {
console.log('Hi, I am ' + this.name);
}
});