tfa
tfa

Reputation: 1699

Reusable Angular Material Dialog and Toast for Information Helper and Alert

I needed to use an suitable alert and helper for my project and found angular material to be awesome. However instead of pasting in the few lines in each controller because I needed to reuse them.

Upvotes: 1

Views: 1678

Answers (1)

tfa
tfa

Reputation: 1699

I needed to set these up as a factory so I can call them from any controller. I find them very helpful might be of use to someone.

Alert

(function () {
    'use strict';
    app.factory("showAlert", ["$mdDialog", function ($mdDialog) {
        return function (title, content, ev) {
            $mdDialog.show(
                $mdDialog.alert()
                .parent(angular.element(document.querySelector('#popupContainer')))
                .clickOutsideToClose(true)
                .title(title)
                .textContent(content)
                .ok('Ok')
                .targetEvent(ev));
        };
    }]);
})();

  1. Called from any controller by passing the factory name 'showAlert' to the controller.
  2. Make sure you pass the '$event' from the html e.g. ng-click="testAlert($event)"
  3. Called as follows

app.controller('someController', showAlert) {
    $scope.testAlert = function(event)
    {
      showAlert('Alert Title Goes Here', 'This is the alert message body.', ev);
    }
}


Information Helper

(function () {
    'use strict';
    app.factory("showHelper", ["$mdToast", "$timeout", function ($mdToast, $timeout) {
        return function (content, startTime, duration) {
            $timeout(function () {
                $mdToast.show(
                    $mdToast.simple()
                    .textContent(content)
                    .position('bottom left')
                    .hideDelay(duration * 1000)
                );
            }, startTime * 1000);
        };
    }]);
})();

  1. Called from any controller by passing the factory name 'showHelper' to the controller.
  2. Pass the message, time to start the helper and the time to end the helper.
  3. Make sure when using more than one helper that the previous helper has ended before the next helper is scheduled to begin
  4. I multiplied by 1000 to use seconds in the controller
  5. Called as follows

app.controller('someController', showHelper) {
	$scope.testAlert = function()
	{
		showHelper('I am the first helper', 1, 4);
		showHelper('I am the second helper', 6, 2);
	}
}

Upvotes: 3

Related Questions