问题
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));
};
}]);
})();
- Called from any controller by passing the factory name 'showAlert' to the controller.
- Make sure you pass the '$event' from the html e.g. ng-click="testAlert($event)"
- 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);
};
}]);
})();
- Called from any controller by passing the factory name 'showHelper' to the controller.
- Pass the message, time to start the helper and the time to end the helper.
- Make sure when using more than one helper that the previous helper has ended before the next helper is scheduled to begin
- I multiplied by 1000 to use seconds in the controller
- 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