Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS click to edit fields such as dropdown

I stumbled upon this article on how to build a click to edit feature for a form. The author states:

What about if you wanted input type="date" or even a select? This is where you could add some extra attribute names to the directive’s scope, like fieldType, and then change some elements in the template based on that value. Or for full customisation, you could even turn off replace: true and add a compile function that wraps the necessary click to edit markup around any existing content in the page.

While looking through the code I cannot seem to wrap my head around how I could manipulate the template in such a way that I could make it apply to any angular component, let alone how I can make it apply to a drop down list. Code from article below:

    app.directive("clickToEdit", function() {
    var editorTemplate = '<div class="click-to-edit">' +
        '<div ng-hide="view.editorEnabled">' +
            '{{value}} ' +
            '<a ng-click="enableEditor()">Edit</a>' +
        '</div>' +
        '<div ng-show="view.editorEnabled">' +
            '<input ng-model="view.editableValue">' +
            '<a href="#" ng-click="save()">Save</a>' +
            ' or ' +
            '<a ng-click="disableEditor()">cancel</a>.' +
        '</div>' +
    '</div>';

    return {
        restrict: "A",
        replace: true,
        template: editorTemplate,
        scope: {
            value: "=clickToEdit",
        },
        controller: function($scope) {
            $scope.view = {
                editableValue: $scope.value,
                editorEnabled: false
            };

            $scope.enableEditor = function() {
                $scope.view.editorEnabled = true;
                $scope.view.editableValue = $scope.value;
            };

            $scope.disableEditor = function() {
                $scope.view.editorEnabled = false;
            };

            $scope.save = function() {
                $scope.value = $scope.view.editableValue;
                $scope.disableEditor();
            };
        }
    };
});

My question is, how can we extend the above code to allow for drop down edits? That is being able to change to the values that get selected.

like image 759
Woot4Moo Avatar asked Mar 22 '23 22:03

Woot4Moo


1 Answers

One approach you might consider is using template: function(tElement,tAttrs ).

This would allow you to return appropriate template based on attributes.

app.directive("clickToEdit", function() {
      return {
       /* pseudo example*/
        template: function(tElement,tAttrs ){
             switch( tAttrs.type){
                 case 'text':
                    return '<input type="text"/>';
                 break;
             }
        },....

This is outlined in the $compile docs

like image 125
charlietfl Avatar answered Mar 30 '23 00:03

charlietfl