Reusable Angular Material Dialog and Toast for Information Helper and Alert

谁说我不能喝 提交于 2019-12-12 10:16:50

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/35999959/reusable-angular-material-dialog-and-toast-for-information-helper-and-alert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!