Skip to content

Instantly share code, notes, and snippets.

@jelbourn
Forked from anonymous/jsbin.EhAnIMaJ.html
Last active April 9, 2016 17:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jelbourn/8015527 to your computer and use it in GitHub Desktop.
Save jelbourn/8015527 to your computer and use it in GitHub Desktop.
Simple angular directive for polymorphism. Running example: http://jsbin.com/EhAnIMaJ/2/edit
var module = angular.module('test', []);
// Simple directive lets you use polymorphism.
module.directive('filter', function() {
return {
scope: {filter: '=filter'},
template: '<div ng-include="filter.url"></div>'
};
});
function PageController($scope, $templateCache) {
$scope.message = 'Polymorphism demo';
// Manually fill the $templateCache so there are no http requests made for the
// templates.
$templateCache.put('range.html',
'<div><input ng-model="filter.min"><input ng-model="filter.max"></div>');
$templateCache.put('text.html',
'<div><input ng-model="filter.text"></div>');
// Each object confirms to an interface. In this example, the only
// requirement is that the object has a "url" property.
$scope.filters = [
{url: 'range.html', min: 0, max: 100},
{url: 'text.html', text: 'World'}
];
}
<!DOCTYPE html>
<html>
<head>
<link href="demo.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<meta charset=utf-8 />
<title>Polymorphism</title>
</head>
<body ng-app="test" ng-controller="PageController">
<h2>{{message}}</h2>
<div class="filter" ng-repeat="filter in filters" filter="filter"></div>
</body>
</html>
.filter {
border: 1px solid black;
padding: 5px;
margin: 5px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment