AngularJS Example
by johnwun
HTML
<div ng-app="testModule">
<div ng-controller="testCtrl">
<p>Editors:</p>
<div ng-repeat="field in fields">
<div class="editor" field-type="field"
editor-model="product[field.name]"></div>
</div>
</div>
</div>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script> <style>
@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');
JavaScript
function testCtrl($scope) {
$scope.fields = [{
name: 'title',
displayName: 'Title',
type: 'text'
}, {
name: 'price',
displayName: 'Price',
type: 'currency'
}];
$scope.product = {
title: 'Test Title',
price: 47.99
}
}
var app = angular.module('testModule', []);
app.directive('editor', function ($compile) {
var textTemplate = '<label class="control-label" for="{{fieldType.name}}">{{fieldType.displayName}}</label>' +
'<div class="controls">' +
'<input id="{{fieldType.name}}" type="text" ng-model="model">' +
'</div>';
var currencyTemplate = '<label class="control-label" for="{{fieldType.name}}">{{fieldType.displayName}}</label>' +
'<div class="controls">' +
'<div class="input-prepend">' +
'<span class="add-on">£</span>' +
'<input id="{{fieldType.name}}" type="text" ng-model="model">' +
'</div>' +
'</div>';
return {
restrict: 'C',
scope: {
fieldType: '=',
model: '=editorModel',
},
link: function(scope, elem, attr){
if(scope.fieldType.type === 'currency'){
elem.html(currencyTemplate);
} else {
elem.html(textTemplate);
}
$compile(elem.contents())(scope);
}
};
});