How to make a double click editable table in AngularJS way?

前端 未结 2 578
不知归路
不知归路 2020-12-15 10:59

Without DOM manipulation, how to make an editable table cell with double click?

I am trying to make it there http://jsfiddle.net/bobintornado/F7K63/35/?

my

相关标签:
2条回答
  • 2020-12-15 11:24

    I updated the fiddle. Is this how you want to do it?

    HTML

    <tr ng-repeat="item in items">
        <td>
            <span ng-hide="item.editing" ng-dblclick="editItem(item)">{{item.name}}</span>
            <input ng-show="item.editing" ng-model="item.name" ng-blur="doneEditing(item)" autofocus />
        </td>
    </tr>
    

    JS

    $scope.items = [{name: "item #1", editing: false}, 
                    {name: "item #2", editing: false}, 
                    {name: "item #3", editing: false}];
    
    $scope.editItem = function (item) {
        item.editing = true;
    }
    
    $scope.doneEditing = function (item) {
        item.editing = false;
        //dong some background ajax calling for persistence...
    };
    

    However you should probably create a directive containing the editable row. And implement the autofocus there, when you dblclick on an item.

    0 讨论(0)
  • I don't like too much the duplicated-element solution so I tried another way and it's working perfectly without complicating the model.

    This is my first contribution so I hope you like guys!

    I use ng-readonly with a condition to protect the input. Ng-repeat assigns a $index to each element iterated so I created a condition for ng-repeat to check if the $index of the element matchs with the $scope.eEditable variable. Then with ng-dblclick I can assign to $scope.eEditable the $index of the element clicked.

    HTML

    <tr ng-repeat="item in items">
        <td>
             <input type="text" value="{{item.name}}" ng-readonly='!($index == eEditable)' ng-dblclick="eEditable = $index"/>
        </td>
    </tr>
    

    CONTROLLER

        $scope.eEditable= -1; //-1 by default. It doesn't match any $index from ng-repeat
    

    One line in controller and two directives in the view, simple and it works

    0 讨论(0)
提交回复
热议问题