【问题标题】:How to bind dynamic content to angular-toastr?如何将动态内容绑定到 angular-toastr?
【发布时间】:2016-02-11 22:02:49
【问题描述】:

我正在使用angular-toastr,我想在 toastr 中有一个动态内容,比如说,一个计数器,我如何在没有其他实例的情况下更新它。

这是我的角脚本:

// Code goes here
angular.module("myApp", ['toastr'])
.controller("myCtrl", myCtrl);

myCtrl.$inject = ["toastr"];

function myCtrl(toastr){
  var vm = this;
  vm.cont = 0;

  vm.start = function(){
    //I need create only one toastr with vm.cont update for each increment
    toastr.info(vm.cont + " en espera", 'Transferencias y pagos', {
      allowHtml: true,    
      extendedTimeOut: 0,
      tapToDismiss: true,
      timeOut: 0,
      onHidden: vm.listWaitView
    });
  };

  vm.increment = function(){
    vm.cont++;
    vm.start(); //function that trigger the toastr
  };
}

我的看法:

 <!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script data-require="angular.js@1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
    <link data-require="angular-toastr@1.3.1" data-semver="1.3.1" rel="stylesheet" href="https://rawgit.com/Foxandxss/angular-toastr/1.3.1/dist/angular-toastr.css" />
    <script data-require="angular-toastr@1.3.1" data-semver="1.3.1" src="https://rawgit.com/Foxandxss/angular-toastr/1.3.1/dist/angular-toastr.tpls.js"></script>

    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="myCtrl as ctrl">
    <h1>Counter</h1>
    <h2>{{ctrl.cont}}</h2>
    <button ng-click="ctrl.increment();">Increment</button>
  </body>

</html>

为方便起见,我制作了一个简单的脚本,并上传到 plunkr:

例子:

https://plnkr.co/edit/w7WbfwyYqkqxQWsAPCZz?p=preview

【问题讨论】:

    标签: javascript angularjs toastr


    【解决方案1】:

    您是否希望在创建新的 toast 之前清除现有的 toast。如果是,请尝试以下操作

    toastr.clear();
    toastr.info(vm.cont + " en espera", 'Transferencias y pagos', {
    ...
    

    这里是笨蛋。 https://plnkr.co/edit/2fnYT6Oi7qzUnhW0KgRo?p=info

    【讨论】:

      【解决方案2】:

      您还可以设置新消息,而无需删除 toast 并按照接受的答案中的建议添加新消息。

      创建 toastr 消息时,您会返回一个 ActiveToast 实例。在这个活动的 toast 上,您可以通过toastrRef 属性访问ToastRef 实例,然后您可以从那里访问属性componentInstance(如果您不使用自己的自定义组件,默认情况下是Toast 的实例)。在这个Toast 实例上,您可以直接设置一条新消息,如下所示:

      const toast: ActiveToast = this.toastr.success('Something just happened');
      const toastComponent: Toast = toast.toastRef.componentInstance;
      setTimeout(
        () => toastComponent.message = 'Toast message has changed', 3000
      );
      

      MikeAlexMartinez 在the following GitHub issue inside the ngx-toastr repository 中提到了这个解决方案:

      希望它对在这里结束的其他人有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-09
        • 1970-01-01
        • 2020-08-30
        • 1970-01-01
        • 2012-12-23
        • 2020-06-16
        • 1970-01-01
        相关资源
        最近更新 更多