Abhishek Abhishek - 4 months ago 20
HTML Question

Click anywhere on body to perform a function: directive

I have created a directive, which will enable a user to click on a word
to edit it in a text box and then whenever and wherever on body is clicked it should get back to the edited word.

html

<div markdown>bineesh</div>


JS Directive

app.directive('markdown',function () {

/*var htmlText='<textarea cols="20" rows="10" ng-show="isEditMode" ng-dblclick="previewSwitch()" ng-model="markdown"></textarea>';*/
var htmlText='<input type="text" class="form-control" ng-hide="isEditMode" ng-dblclick="backToTextarea()" ng-model="markdown"/>';
var newHtml='<div ng-click="previewSwitch()" ng-show="isEditMode" >{{markdown}}</div>'
var dir={
restrict:'A',
compile:function (tElement,tAttrs,transclude) {
var markdown=tElement.text();

tElement.html(htmlText);
tElement.append(newHtml);

return function (scope,element,attrs) {
scope.isEditMode=true;
scope.markdown=markdown;

scope.previewSwitch=function () {
scope.isEditMode=false;
}
scope.backToTextarea=function () {
scope.isEditMode=true;
}
};


}
}
return dir;
});


I know that something needs to be added in the directive, but I am not getting into it properly, as I am new to Angular

Answer
angular.element(document).on('click', function() {
  scope.isEditMode = false;
});

element.on('click', function(e) {
  e.stopPropagation();
  return false;
});