javascript - 有没有办法避免重复代码?
问题描述
如何通过在javascript中提供方法作为参数来删除重复代码?下面是代码。
var toastrService = function (toastr) {
var _toastrService = this;
_toastrService.success =function(message,title) {
toastr.success(message,title);
}
_toastrService.info =function(message,title) {
toastr.info(message,title);
}
_toastrService.error =function(message,title) {
toastr.error(message,title);
}
_toastrService.warning =function(message,title) {
toastr.warning(message,title);
}
_toastrService.success =function(message,title) {
toastr.success(message,title);
}
}
解决方案
要使全局属性可注入,只需将其声明为 AngularJS 值:
angular.module("app",[]).value("toastrService", toastr);
然后在需要的地方注入:
app.controller("ctrl", function (toastrService) {
toastrService.info("Title","Message");
});
有关详细信息,请参阅
推荐阅读
- python - ModbusTcpClient 操作返回什么对象?
- python - 根据重复的列值提取数据帧行并将它们存储在新的数据帧中
- html - 为什么会出现此错误 label 元素的 for 属性的值必须是非隐藏表单控件的 ID
- javascript - Android 上的 React Native/Expo 中没有匹配的活动错误
- java - WebClientResponseException$NotFound: 404 未找到
- c# - 如果主线程死锁,Application Insights 不会刷新?
- devops - 如何在 grafana 的地理显示上呈现时间序列数据?
- c# - 如何在aspx中从父页面初始化子ascx控件的值?
- docker - docker-compose 中的 Traefik 自签名证书通配符子域
- javascript - 使用屏幕分辨率动态响应定位组件