AngularJS custom directive
First attempt at a custom directive
HTML
<div ng:app="zdamModule">
<div ng:controller="Ctrl3">
<my:Editable my-data="someData}></my:Editable>
<hr/>
Debug: {{someData}}
</div>
</div>
CSS
</style>
<script src="http://docs-next.angularjs.org/angular-0.10.6.min.js"></script>
<style>
.ng-invalid { border: 1px solid red; }
body { font-family: Arial,Helvetica,sans-serif; }
body, td, th { font-size: 14px; margin: 0; }
table { border-collapse: separate; border-spacing: 2px; display: table; margin-bottom: 0; margin-top: 0; -moz-box-sizing: border-box; text-indent: 0; }
a:link, a:visited, a:hover { color: #5D6DB6; text-decoration: none; }
.error { color: red; }
JavaScript
function Ctrl3($scope) {
$scope.someData= 'Lorem Ipsum';
}
angular.module('zdamModule', [])
.directive('myEditable', function($compile){
return {
replace: true,
transclude: true,
scope: {
myData:'bind'
},
template: '<label>{{myData}}</label>',
// The linking function will add behavior to the template
link: function(scope, element, attrs) {
function setReadOnly(element) {
var readOnlyTemplate = '<label>{{myData}}</label>';
element.html(readOnlyTemplate);
$compile(element.contents())(scope);
scope.$digest();
angular.element(element).bind('click', function(){setEditable(element)});
}
function setEditable(element) {
var editableTemplate = '<input type="text" value="{{myData}}"/>';
angular.element(element).unbind('click');
element.html(editableTemplate);
$compile(element.contents())(scope);
scope.$digest();
var textbox = angular.element(element.contents()[0]);
textbox.bind('blur', function(){setReadOnly(element)});
}
function init(element){
angular.element(element).bind('click', function(){setEditable(element)});
}
// initialize the directive
init(element);
}
}
});