Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Morph label into input

Tags:

angularjs

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).

like image 583
xanadont Avatar asked Dec 05 '25 05:12

xanadont


1 Answers

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();
                });
            });

        }]
    };
});
like image 111
Scottux Avatar answered Dec 07 '25 22:12

Scottux