2

ライブデモ

confirmationDialogHeader次のように使用されるディレクティブを作成しました。

<ul>
  <li ng-repeat="item in items">
    {{item}}
    <button class="btn btn-mini" 
            confirmation-dialog-header="Delete Item" 
            confirmation-dialog-action="deleteItem($index)">
      Delete
    </button>
  </li> 
</ul>

ボタンをクリックすると、確認ダイアログが開き、ユーザーが確認すると、 を呼び出しdeleteItem($index)てダイアログを閉じます。

私の問題は最後のビットにあります:ダイアログを閉じます。

コントローラー (CoffeeScript) は次のとおりです。

app.controller 'AppCtrl', ['$scope', '$q', '$timeout', ($scope, $q, $timeout) ->
  $scope.items = ['Item 1', 'Item 2'] 
  $scope.deleteItem = (index) ->                         
    deferred = $q.defer()
    $timeout ->
      $scope.items.splice(index, 1)   # All good if this line is removed
      deferred.resolve()
    , 1000
    deferred.promise
]

そして、ここにディレクティブがあります:

app.directive 'confirmationDialogHeader', ['$compile', '$q', ($compile, $q) ->
  restrict: 'A'
  scope:
    confirmationDialogAction: '@'
  controller: ($scope) ->
    $scope.onConfirm = ->
      $scope.$parent.$eval($scope.confirmationDialogAction).then ->
        $scope.confirmationDialog = off   # Why this doesn't close the dialog?
  link: (scope, element, attrs) -> 
    $confirmationDialog = $ """
      <div modal="confirmationDialog">
        <div class="modal-header">
          <h4>#{attrs.confirmationDialogHeader}</h4>
        </div>
        <div class="modal-body">
          Are you sure?
        </div>
        <div class="modal-footer">
          <button class="btn" ng-click="confirmationDialog = false">
            Cancel
          </button>
          <button class="btn" ng-click="onConfirm()">
            Yes
          </button>
        </div>
      </div>
    """

    $(document.body).append($confirmationDialog)
    $compile($confirmationDialog)(scope)

    $(element).click ->
      scope.$apply ->
        scope.confirmationDialog = yes  

]

ご覧のとおり、ダイアログは終了後に閉じられずdeleteItem()、実行$scope.confirmationDialog = offされます。

興味深いのは、 を$scope.items.splice(index, 1)でラップすると$timeout、ダイアログ適切に閉じられることです。

$timeout ->
  $scope.items.splice(index, 1)

なぜこの$timeoutラッピングがここで必要なのですか?

いつコードをラップするべきかについてのガイドラインはあります$timeoutか?


を使用するこのディレクティブの作業バージョン$dialog


4

1 に答える 1

2

コードを $timeout でいつラップするべきかについてのガイドラインはありますか?

$timeout は、ネイティブの setTimeout の代わりとして使用されます。ネイティブ タイムアウトに対する利点は、try/catch ブロックでコールバックが実行され、発生したエラーがアプリケーションの exceptionHandler サービスに転送されることです。

ただし、私が見ている問題ではなく、コードを単純化できるデモで遊んでいます。

更新 モーダルダイアログを使用して特定の実装を機能させたいと思っていましたが、あまり運がありませんでした。そのため、モーダル ディレクティブではなく $dialog サービスを使用して実装しました。多分それは役立つでしょう-ここにあります

また、元のバージョンでは、[はい] をクリックしてダイアログを閉じたときにスコープが更新されていて、ダイジェスト内で発生していたため、ウォッチャーを起動してダイアログを閉じる必要があることがわかりました。その点で、タイムアウトが使用されているかどうかに関係なく、ブラウザで何らかの理由で機能しなかった理由がわかりません。

于 2013-06-11T11:13:45.573 に答える