Edit In Place Content Editing

前端 未结 4 1751
暗喜
暗喜 2020-12-04 06:02

When using ng-repeat what is the best way to be able to edit content?

In my ideal situation the added birthday would be a hyperlink, wh

4条回答
  •  执念已碎
    2020-12-04 06:26

    I was looking for a inline editing solution and I found a plunker that seemed promising, but it didn't work for me out of the box. After some tinkering with the code I got it working. Kudos to the person who made the initial effort to code this piece.

    The example is available here http://plnkr.co/edit/EsW7mV?p=preview

    Here goes the code:

    app.controller('MainCtrl', function($scope) {
    
      $scope.updateTodo = function(indx) {
        console.log(indx);
      };
    
      $scope.cancelEdit = function(value) {
        console.log('Canceled editing', value);
      };
    
      $scope.todos = [
        {id:123, title: 'Lord of the things'},
        {id:321, title: 'Hoovering heights'},
        {id:231, title: 'Watership brown'}
      ];
    });
    
    // On esc event
    app.directive('onEsc', function() {
      return function(scope, elm, attr) {
        elm.bind('keydown', function(e) {
          if (e.keyCode === 27) {
            scope.$apply(attr.onEsc);
          }
        });
      };
    });
    
    // On enter event
    app.directive('onEnter', function() {
      return function(scope, elm, attr) {
        elm.bind('keypress', function(e) {
          if (e.keyCode === 13) {
            scope.$apply(attr.onEnter);
          }
        });
      };
    });
    
    // Inline edit directive
    app.directive('inlineEdit', function($timeout) {
      return {
        scope: {
          model: '=inlineEdit',
          handleSave: '&onSave',
          handleCancel: '&onCancel'
        },
        link: function(scope, elm, attr) {
          var previousValue;
    
          scope.edit = function() {
            scope.editMode = true;
            previousValue = scope.model;
    
            $timeout(function() {
              elm.find('input')[0].focus();
            }, 0, false);
          };
          scope.save = function() {
            scope.editMode = false;
            scope.handleSave({value: scope.model});
          };
          scope.cancel = function() {
            scope.editMode = false;
            scope.model = previousValue;
            scope.handleCancel({value: scope.model});
          };
        },
        templateUrl: 'inline-edit.html'
      };
    });
    

    Directive template:

    {{model}} edit

    To use it just add water:

    UPDATE:

    Another option is to use the readymade Xeditable for AngularJS:

    http://vitalets.github.io/angular-xeditable/

提交回复
热议问题