3

What is the proper way in Angular to switch data into "edit mode" where <label>'s get morphed into <input type='text'>'s? I'd like to create and destroy the DOM elements at runtime instead of rendering all the inputs first as hidden (where they are then shown, and labels hidden, when switched to edit mode).

xanadont
  • 7,493
  • 6
  • 36
  • 49
  • You can use `input`s and play with their `ng-disabled` property , also for style them as labels while "not editing" mode – Ivan Chernykh Jul 26 '13 at 13:51
  • What about [contenteditable](http://html5demos.com/contenteditable) [directive](http://jsfiddle.net/api/post/library/pure/)? – madhead Jul 26 '13 at 13:51
  • You can look at `ng-if` that is part of angular 1.1.5 – Chandermani Jul 26 '13 at 14:02
  • As @cherniv mentions above using the `ng-disabled` on the `input` element is the easiest way to deal with this but, if you really do want to switch between elements then you could write a directive with transclusion enabled. Then switch back and forth between edit mode and rendered mode. see this video for a tutorial: [AngularJS - Custom Components - Part 2](http://www.youtube.com/watch?v=nKJDHnXaKTY) – winkerVSbecks Jul 26 '13 at 15:53
  • Thanks for the tips, all. I'll finally be able to look into it this week. – xanadont Jul 31 '13 at 13:34
  • The thing you looked for is called inline editing or in-place editing. There's another question about it here: http://stackoverflow.com/questions/15453254/angular-js-edit-in-place-content-editing This comment is to help others find this Q&A better. – Christiaan Westerbeek Feb 07 '17 at 10:03

1 Answers1

2

Something along the lines of this jsfiddle should work for you. It is still hiding/showing but the input doesn't need to be in the DOM up front. There are probably a million alternative ways to handle this, but I thought this would at least demonstrate how to get the functionality into a directive.

HTML:

<label inline-edit>Edit me</label>

Directive:

'use strict';
var app = angular.module('myApp', []);
app.directive('inlineEdit', function() {
    return{
        restrict: 'A',
        transclude: true,
        template: '<label class="editing" data-ng-transclude></label>',
        controller: ['$scope','$element','$transclude',function($scope, $element, $transclude) {
            $transclude(function(clone) {
                $scope.transcluded_content = clone[0].textContent;
            });
            $element.bind('click', function(){
                $element.hide().after('<input type="text" value="'+$scope.transcluded_content+'" />');

                $element.next().focus().blur(function (){
                    $scope.transcluded_content = $element.next().val();
                    $element.html($scope.transcluded_content);
                    $element.next().hide();
                    $element.show();
                });
            });

        }]
    };
});
Scottux
  • 1,577
  • 1
  • 11
  • 22