5

ngrepeat でレンダリングされ、xeditable を使用して自動的に編集可能にする新しいアイテムをコレクションに追加する必要があります。

ところで、xeditable には「手動トリガー」方式を使用しています。

ここにHTMLがあります

<h4>Angular-xeditable demo</h4>
<div ng-app="app" ng-controller="Ctrl" style="margin: 50px">
<div class="btn btn-default" ng-click="addNew()">+</div>
<ul>
  <li ng-repeat="item in array | orderBy:'-value'">
    <a href="#" e-form="itemForm" editable-text="item.field">{{ item.field }}</a>
    <i ng-show="!itemForm.$visible" ng-click="itemForm.$show()">edit</i>
  </li>
</ul>
</div>

そしてここにコントローラーがあります:

var app = angular.module("app", ["xeditable"]);

app.run(function(editableOptions) {
  editableOptions.theme = 'bs3';
});

app.controller('Ctrl', function($scope, $filter) {

  $scope.array = [
    {value: 1, field: 'status1'},
    {value: 2, field: 'status2'},
    {value: 3, field: 'status3'},
    {value: 4, field: 'status4'}
  ]; 

  $scope.addNew = function(){
    $scope.array.push({value:$scope.array.length+1, field: 'enter text here'});
    //MAKE IT EDITABLE????????
  }
});

このフィドルの問題を見てください: http://jsfiddle.net/dpamio/hD5Kh/1/

4

2 に答える 2

3

これが機能する更新されたフィドルです。ディレクティブがどのように記述され、どのように機能するかにより、非常にハックなソリューションng-repeatが必要でした...

app.controller('Ctrl', function($scope, $filter, $timeout) {

  $scope.itemForms = {};

  $scope.addNew = function(){
    $scope.array.push({value:$scope.array.length+1, field: 'enter text here'});

     // Use timeout to force evaluation after the element has rendered
     // ensuring that our assignment expression has run
     $timeout(function() {
         $scope.itemForms[0].$show(); // last index since we sort descending, so the 0 index is always the newest
     })
  }

ng-repeat の仕組みの背景: ng-repeat は、繰り返される各要素に対して新しい子スコープを作成します。e-formディレクティブは、その名前 (この場合は) に渡された文字列を使用して、そのスコープに変数を割り当てますitemForm。よりスマートであれば、代入の式評価が可能になります。(次に、それを親スコープに割り当てて、コントローラーでアクセスできますが、それは別の問題です)。

ディレクティブの外でこの子スコープにアクセスする方法がないため、非常に悪いことをします。後で使用できるように、display none のスパンで mustache 式を使用してitemForm変数を親スコープに割り当てます。次に、コントローラー内でルックアップ値を使用して、itemForm.$show()期待するメソッドを呼び出します。

その厄介な部分を角度ディレクティブに抽象化すると、次のように記述できます。

.directive('assignFromChild', function($parse) {
    return {
        restrict: 'A',
        link: function(scope, el, attrs) {
            scope.$watch(function() { return $parse(attrs.assignFromChild)(scope); }, function(val) {
                $parse('$parent.' + attrs.toParent).assign(scope, val);
            })
        }
    }; 
});

HTML を次の場所に戻します。

<ul>   
  <li ng-repeat="item in array | orderBy:'-value'" assign-from-child="itemForm" to-parent="itemForms[{{$index}}]">
    <a href="#" e-form="itemForm" editable-text="item.field">{{ item.field }}</a>
    <i ng-show="!itemForm.$visible" ng-click="itemForm.$show()">edit</i>
  </li>
</ul>

これが私の最終的な解決策のフィドルです

于 2015-02-28T07:26:50.350 に答える