我创建了一个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
?