首页 > 解决方案 > 有没有办法避免重复代码?

问题描述

如何通过在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);
  }

}

标签: javascriptangularjs

解决方案


要使全局属性可注入,只需将其声明为 AngularJS 值:

angular.module("app",[]).value("toastrService", toastr);

然后在需要的地方注入:

app.controller("ctrl", function (toastrService) {
    toastrService.info("Title","Message");
});

有关详细信息,请参阅


推荐阅读