Search code examples
javascriptangularjstoastr

How to bind dynamic content to angular-toastr?


I'm using angular-toastr, and I want to have a dynamic content inside toastr, let's say, a counter, how can I update it with no other instance.

Here is my angular script:

// 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
  };
}

My view:

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

  <head>
    <script data-require="[email protected]" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
    <link data-require="[email protected]" data-semver="1.3.1" rel="stylesheet" href="https://rawgit.com/Foxandxss/angular-toastr/1.3.1/dist/angular-toastr.css" />
    <script data-require="[email protected]" 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>

For your convenience I made a simple script that I uploaded in plunkr:

Example:

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


Solution

  • Are you looking for clearing the existing toasts before creating new one. If yes, then try the below

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

    Here is the plunker. https://plnkr.co/edit/2fnYT6Oi7qzUnhW0KgRo?p=info