我对Angular有点陌生。在我的一个控制器中,我正在设置烤面包机上的一些全局选项,并调用烤面包机通过工厂暴露的方法(tndNotifier)。这似乎很管用,但我不喜欢当我点击烤面包机中除"继续"按钮或"x"以外的任何按钮时div,最后调用onclick事件。我试图完全忽略这一点,这样用户不会意外地调用onclick事件。这似乎不可能,但我可能错了。此外,单击按钮不会关闭烤面包机实例。
promptForDeleteServiceLog: function(serviceLog) {
// I am sure I can hide toastr behind some other abstraction to avoid a direct reference
toastr.options = {
tapToDismiss: false,
closeButton: true,
onclick: function(object) {
$scope.tndServiceLogList.deleteServiceLog(serviceLog);
}
};
// Embedding markup here makes me feel dirty
tndNotifier.warn('You are about to delete ' + serviceLog.description + '. Click 'Continue' to delete or 'x' to cancel.' +
' <br><br><button class="btn btn-warning">Continue</button>');
}
工厂定义如下:
angular.module('app').value('tndToastr', toastr);
angular.module('app').factory('tndNotifier', function(tndToastr) {
return {
notify: function(msg) {
tndToastr.success(msg);
console.log(msg);
},
warn: function(msg) {
tndToastr.warning(msg);
console.log(msg);
},
error: function(msg) {
tndToastr.error(msg);
console.log(msg);
}
}
});
我之所以使用toast,是因为它为我提供了一个通用的通知机制。我应该以这种方式使用toast(用于确认对话框),还是应该编写一个自定义指令来弹出一个div,而根本不使用toast?我的用例的首选方法是什么?
我有一个想法,也许我应该在指令中使用jQuery,试图实现与toast类似的外观和感觉(以及行为),但我不知道最好的方法。
这个jsfiddle说明了我上面描述的内容。
基于您的小提琴:
您正在设置配置对象的toastr
全局与tndToastr
value
提供程序不同,因此在tndToaster上调用事件不会尊重您传递的配置。:
// Wrong Way.
myApp.controller('MyCtrl', function ($scope, tndNotifier) {
$scope.tndServiceLogList = {
promptForDeleteServiceLog: function (serviceLog) {
toastr.options = { //This is not the same toastr variable as your injectable tndToastr that you defined, so therefore calling events on tndToaster wont resepct this config.
tapToDismiss: false,
closeButton: true
};
tndNotifier.warn('You are about to delete FOO. Click 'Continue' to delete or 'x' to cancel.' +
' <br><br><button class="btn btn-warning">Continue</button>');
} };
});
注入tndToaster
并对其进行配置:
如果您按照如下所示注入您的值,然后调用它上的配置,您就会看到您想要的行为。
// Way that does work in updated fiddle
myApp.controller('MyCtrl', function ($scope, tndNotifier, tndToastr) {
$scope.tndServiceLogList = {
promptForDeleteServiceLog: function (serviceLog) {
tndToastr.options = {
tapToDismiss: false,
closeButton: true
};
tndNotifier.warn('You are about to delete FOO. Click 'Continue' to delete or 'x' to cancel.' +
' <br><br><button class="btn btn-warning">Continue</button>');
} };
});
这是带有更新控制器的更新的FIDDLE。
旁注:我应该使用toast通知作为模式吗
Seth Flowers提出了一个很好的观点,即您可能不应该使用通知库来生成UI/UX中看起来像模态的内容。然而,如果它像鸭子一样走路,像鸭子一样说话,那么它就是一只鸭子。如果它拥有你所需要的所有功能,而不必从中得到任何东西,那么我相信它使用起来可能是安全的。我建议查看上面的ui模态组件或其他选项http://ngmodules.org/.