Как редактировать содержимое в Angular js Smart Table

Я новичок в java script, поэтому я должен извиниться, если это кажется простым.

Как я могу редактировать таблицы строк в Smart-Table с помощью Angularjs? Похоже, что нет учебника по новому Smart-Table. Я хотел бы создать простую форму для пользователей, чтобы ввести часы, открытые для определенного места.

Я создал кнопки, которые могут добавлять и удалять строки в таблице, но когда я добавляю contenteditable="true" ни одно из изменений не сохраняется при обновлении объекта. Я понимаю, что contenteditable - это определенные параметры html5, независимые от смарт-таблицы, но я не понимаю, как еще я могу обновить данные или как я могу получить обновленные данные.

Данные извлекаются из контроллера angularjs через маршруты mean.js.

<div class="controls">
    <table st-table="place.openHours" class="table table-striped">
        <thead>
        <tr>
            <th>Day</th>
            <th>Opening Time</th>
            <th>Closing Time</th>
        </tr>
        </thead>
        <tbody>
        <tr ng-repeat="row in place.openHours" contenteditable="true" >
            <td>{{row.day}}</td>
            <td>{{row.open}}</td>
            <td>{{row.close}}</td>
            <button type="button" ng-click="removeOpenHour(row)" class="btn btn-sm btn-danger">
                <i class="glyphicon glyphicon-remove-circle">
                </i>
            </button>
        </tr>
        </tbody>
    </table>

    <button type="button" ng-click="addOpenHour(row)" class="btn btn-sm btn-success">
        <i class="glyphicon glyphicon-plus">
        </i> Add new Row
    </button>
</div>

Внутри javascript:

    $scope.removeOpenHour = function removeOpenHour(row) {
        var index = $scope.place.openHours.indexOf(row);
        if (index !== -1) {
            $scope.rowCollection.splice(index, 1);
        }
    }

    $scope.addOpenHour = function addOpenHour() {
        $scope.place.openHours.push(
        {
            day: 'Monday',
            open: 540,
            close: 1080
        });
    };

person user2557625    schedule 11.02.2015    source источник
comment
Я думаю, вам нужно проделать немного больше работы, чтобы использовать contenteditable в Angular. Он напрямую изменяет дом, и вам нужно поймать эти изменения, чтобы Angular знал о них. github.com/akatov/angular-contenteditable/blob/master/   -  person elpddev    schedule 11.02.2015


Ответы (2)


Спасибо, я осмотрелся и использовал код отсюда http://jsfiddle.net/bonamico/cAHz7/ и объединил его со своим кодом.

HTML-файл:

<tr ng-repeat="row in place.openHours">
   <td><div contentEditable="true" ng-model="row.day">{{row.day}}</div></td>
   <td><div contentEditable="true" ng-model="row.open">{{row.open}}</div></td>
   <td><div contentEditable="true" ng-model="row.close">{{row.close}}</div></td>
   <td>
   <button type="button" ng-click="removeOpenHour(row)" class="btn btn-sm btn-danger">
      <i class="glyphicon glyphicon-remove-circle">
      </i>
   </button>
</td>

JS file:

myApp.directive('contenteditable', function() {
return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
        // view -> model
        elm.bind('blur', function() {
            scope.$apply(function() {
                ctrl.$setViewValue(elm.html());
            });
        });

        // model -> view
        ctrl.render = function(value) {
            elm.html(value);
        };

        elm.bind('keydown', function(event) {
            console.log("keydown " + event.which);
            var esc = event.which == 27,
                el = event.target;

            if (esc) {
                console.log("esc");
                ctrl.$setViewValue(elm.html());
                el.blur();
                event.preventDefault();
            }

        });

    }
};
});
person user2557625    schedule 13.02.2015
comment
Contenteditable не поддерживается ни в одной версии IE. Так бесполезно. - person DotNetGeek; 25.06.2015
comment
@DotNetGeek: Не знаю, почему это делает его бесполезным. Возможно, IE не должен так сильно отставать. - person PritishC; 05.08.2015

Мое решение таково:

Угловая директива:

app.directive("markdown", function() {

  return {
    restrict: 'EA',
    scope: {

        value: '='},
    template: '<span ng-click="edit()" ng-bind="value"></span><input ng-blur="blur()" ng-model="value"></input>',
    link: function($scope, element, attrs) {
        // Let's get a reference to the input element, as we'll want to reference it.
        var inputElement = angular.element(element.children()[1]);

        // This directive should have a set class so we can style it.
        element.addClass('edit-in-place');

        // Initially, we're not editing.
        $scope.editing = false;

        // ng-click handler to activate edit-in-place
        $scope.edit = function() {
            $scope.editing = true;

            // We control display through a class on the directive itself. See the CSS.
            element.addClass('active');

            // And we must focus the element. 
            // `angular.element()` provides a chainable array, like jQuery so to access a native DOM function, 
            // we have to reference the first element in the array.
            inputElement[0].focus();
        };

        // When we leave the input, we're done editing.

        $scope.blur = function() {
            $scope.editing = false;
            element.removeClass('active');
        }
    }
  };

});

HTML:

 <table st-table="displayedCollection" st-safe-src="rowCollection" class="table table-striped">

    <thead>
      <tr>
          <th st-sort="sku">SKU</th>
          <th st-sort="skuSupplier">SKU proveedor</th>
          <th st-sort="name">Descripción</th>
          <th st-sort="cantidad">Cantidad</th>
          <th st-sort="precio">Precio unitario</th>
          <th st-sort="total">Total</th>
      </tr>
      <tr>
          <th colspan="5"><input st-search="" class="form-control" placeholder="Buscar producto ..." type="text"/></th>
          </tr>
    </thead>
    <tbody>
       <tr ng-repeat="row in displayedCollection">
          <td><markdown value="row.sku"></markdown></td>
          <td><markdown value="row.skuSupplier"></markdown></td>
          <td><markdown value="row.name"></markdown></td>
          <td><markdown value="row.cantidad"></markdown></td>
          <td><markdown value="row.precio"></markdown></td>
          <td><markdown value="row.total"></markdown></td>
          <td>
              <button type="button" ng-click="removeItem(row)" class="btn btn-sm btn-danger">
                 <i class="glyphicon glyphicon-remove-circle"></i>
              </button>
          </td>
      </tr>
    </tbody>
  </table>
person Mmeza-developer    schedule 16.12.2015
comment
Всякий раз, когда я что-то набираю в текстовое поле, оно отображается дважды, одно внутри текстового поля, а другое вне текстового поля, не могли бы вы взглянуть? @user3809100 - person Badhon Jain; 06.01.2016