stackoverflow: Whats the solution here? want to re-use the same controller with different data
http://stackoverflow.com/questions/23309425/whats-the-solution-here-want-to-re-use-the-same-controller-with-different-data
by chucknelson
HTML
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<div id="mainContainer" ng-app="angularGrid" ng-controller="MainCtrl">
<div id="gridSelectionButtons">
<span>Grid Model Selection:</span>
<input type="radio" id="usersButton" ng-model="gridSelection" value="Users" select="true">Users</input>
<input type="radio" id="groupsButton" ng-model="gridSelection" value="Groups">Groups</input>
</div>
<div id="theGrid" class="grid">
<div class="grid-header">
<h3>Showing Grid for {{gridSelection}}</h3>
</div>
</div>
<p class="footerText">AngularJS {{angularVersionText}}</p>
</div>
CSS
.footerText {
font-size: .8em;
color: #888;
}
JavaScript
'use strict';
var app = angular.module('angularGrid', []);
app.controller('MainCtrl', ['$scope', 'Users', 'Groups', function($scope, Users, Groups) {
$scope.angularVersionText = angular.version.full + ', "' + angular.version.codeName + '"';
$scope.gridSelection = 'Users'; /* default */
}]);
/* example factories */
app.factory('Users', function() {
var usersInstance = {};
usersInstance.get = function() {
return [
{id:1, fullName: 'User 1', emailAddress: '[email protected]'},
{id:2, fullName: 'User 2', emailAddress: '[email protected]'},
{id:3, fullName: 'User 3', emailAddress: '[email protected]'}
];
};
return usersInstance;
});
app.factory('Groups', function() {
var groupsInstance = {};
groupsInstance.get = function() {
return [
{id:1, name: 'Group 1'},
{id:2, name: 'Group 2'}
];
};
return groupsInstance;
});
//somewhat generic sorting directive which requires and wraps jQuery UI sortable
//applied to any parent container, and the immediate child elements become sortable
//child elements must contain a hidden input named "id" that is a unique identifier for that element/data
//when the update() callback is triggered (via jquery ui sortable) the directive provides an itemUpdates collection that contains JS objects defined as {id, newSortOrder} for all elements that have a changed sort order and also calls the method defined in the on-sort property for the directive. Common usage is to pass itemUpdates to a method in your controller that updates the model represented by the sortable list.
app.directive('cnSortable', function() {
return {
//isolate scope
scope: {
onSort: '&'
},
compile: function(tElement, tAttrs) {
//could use compile if we needed to set up some common functionality for all instances. Since this is just a one-instance directive on my page right...