任何控制器angularjs中的火灾通知烤面包机

Fire notification toaster in any controller angularjs

本文关键字:通知 烤面包 面包机 火灾 控制器 angularjs 任何      更新时间:2023-09-26

我正在使用此服务进行通知:https://github.com/jirikavi/AngularJS-Toaster
工作正常。在我的应用程序中,我已经为此进行了配置,我创建了一个pop()按钮,点击触发通知烤面包机
我现在需要的是我的应用程序中的任何控制器,可以调用触发通知方法
例如,在控制器ProductController中,我随时调用pop(),然后会触发通知
尽管有任何视图,但控制器中的pop()方法功能根本不起作用
有什么细节我没有看?

我的index.html

<!DOCTYPE html>
<html lang="en" data-ng-app="app">
<head>
  <meta charset="utf-8" />
  <title>My App</title>
  <meta name="description" content="app, web app, responsive, responsive layout, admin, admin panel, admin dashboard, flat, flat ui, ui kit, AngularJS, ui route, charts, widgets, components" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <link rel="stylesheet" href="css/bootstrap.css" type="text/css" />
  <link rel="stylesheet" href="css/animate.css" type="text/css" />
  <link rel="stylesheet" href="css/font-awesome.min.css" type="text/css" />
  <link rel="stylesheet" href="css/simple-line-icons.css" type="text/css" />
  <link rel="stylesheet" href="css/font.css" type="text/css" />
  <link rel="stylesheet" href="css/app.css" type="text/css" />
  <link rel="stylesheet" href="js/modules/toaster/toaster.css" type="text/css" />
</head>
<body ng-controller="AppCtrl">
  <div class="app" id="app" ng-class="{'app-header-fixed':app.settings.headerFixed, 'app-aside-fixed':app.settings.asideFixed, 'app-aside-folded':app.settings.asideFolded, 'app-aside-dock':app.settings.asideDock, 'container':app.settings.container}" ui-view></div>
  <!-- jQuery -->
  <script src="js/jquery/jquery.min.js"></script>
  <!-- Angular -->
  <script src="js/libs/angular/angular.js"></script>
  <script src="js/libs/angular/angular-cookies.js"></script>
  <script src="js/libs/angular/angular-animate.js"></script>
  <script src="js/libs/angular/angular-resource.js"></script>
  <script src="js/libs/angular/angular-ui-router.js"></script>
  <script src="js/libs/angular/ngStorage.js"></script>
  <script src="js/libs/angular/ocLazyLoad.js"></script>
  <script src="js/libs/angular/ui-bootstrap-tpls.js"></script>
  <script src="js/angular/angular-translate.js"></script>
  <script src="js/angular/ui-jq.js"></script>
  <script src="js/angular/ui-load.js"></script>
  <script src="js/angular/ui-validate.js"></script>
  <!-- App -->
  <script src="js/app.js"></script>
  <script src="js/services.js"></script>
  <script src="js/controllers.js"></script>
  <script src="js/controller-university.js"></script>
  <script src="js/filters.js"></script>
  <script src="js/directives.js"></script>
  <script src="js/modules/toaster/toaster.js"></script>
  <!-- Lazy loading -->
</body>
</html>

当通知烤面包机被点击"pop()"时的我的视图(它工作得很好):

<div class="bg-light lter b-b wrapper-md">
  <h1 class="m-n font-thin h3">Universities</h1>
</div>
<div class="wrapper-md">
  <!-- toaster directive -->
  <toaster-container toaster-options="{'position-class': 'toast-top-right', 'close-button':true}"></toaster-container>
  <!-- / toaster directive -->
      <div class="col-sm-6">
        <form name="formCreate" class="form-validation"  ng-submit="insert()">
          <div class="panel panel-default">
            <div class="panel-heading">
              <span class="h4">Create</span>
            </div>
            <div class="panel-body">
              <div class="form-group pull-in clearfix">
                <div class="col-sm-6">
                  <label>Nome</label>
                  <input type="text" name="name" class="form-control" maxlength="40" ng-model="university.name" required >
                </div>
              </div><!--./form-group-->
            </div>
            <footer class="panel-footer text-right bg-light lter">
              <button type="submit" class="btn btn-success">Save</button>
              <button class="btn btn-success" ng-click="pop()">pop()</button>
            </footer>
          </div>
        </form>
      </div>
</div>

我的控制器:

'use strict';
angular.module('app.controller-university', ['ngCookies'])
  .controller('UniversityCtrl', ['$stateParams', '$scope', '$window', 'University',
    function($stateParams, $scope, $window, University ) {
      $scope.pop();       
  }]);

文件controllers.js。AppCtrl:在哪里

'use strict';
/* Controllers */
angular.module('app.controllers', ['pascalprecht.translate', 'ngCookies'])
  .controller('AppCtrl', ['$rootScope', '$scope', '$translate', '$localStorage', '$window', 'toaster', 
    function(              $rootScope,   $scope,   $translate,   $localStorage,   $window,   toaster ) {
      // add 'ie' classes to html
      var isIE = !!navigator.userAgent.match(/MSIE/i);
      isIE && angular.element($window.document.body).addClass('ie');
      isSmartDevice( $window ) && angular.element($window.document.body).addClass('smart');
      $scope.toaster = {
          type: 'success',
          title: 'Title',
          text: 'Message'
      };
      $scope.pop = function(){
          toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
      };
  }])

这是我的app.js

'use strict';

// Declare app level module which depends on filters, and services
var app = angular.module('app', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngStorage',
    'ui.router',
    'ui.bootstrap',
    'ui.load',
    'ui.jq',
    'ui.validate',
    'oc.lazyLoad',
    'pascalprecht.translate',
    'app.filters',
    'app.services',
    'app.directives',
    'app.controllers',
    'app.controller-university',
    'UniversityService',
    'toaster',
  ])
.run(
  [          '$rootScope', '$state', '$stateParams',
    function ($rootScope,   $state,   $stateParams) {
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;        
    }
  ]
)
.config(
  [          '$stateProvider', '$urlRouterProvider', '$controllerProvider', '$compileProvider', '$filterProvider', '$provide',
    function ($stateProvider,   $urlRouterProvider,   $controllerProvider,   $compileProvider,   $filterProvider,   $provide) {
        // lazy controller, directive and service
        app.controller = $controllerProvider.register;
        app.directive  = $compileProvider.directive;
        app.filter     = $filterProvider.register;
        app.factory    = $provide.factory;
        app.service    = $provide.service;
        app.constant   = $provide.constant;
        app.value      = $provide.value;
        $urlRouterProvider
            .otherwise('/app/dashboard-v1');
        $stateProvider
            .state('app', {
                abstract: true,
                url: '/app',
                templateUrl: 'tpl/app.html',              
            })
            .state('app.dashboard-v1', {
                url: '/dashboard-v1',
                templateUrl: 'tpl/app_dashboard_v1.html'
            })
            /////////////////////////
            // University
            //////////////////////////////////////////
            .state('app.university', {
                url: '/universidade',
                template: '<div ui-view class="fade-in-up"></div>'
            })
            .state('app.university.list', {
                url: '/listar',
                templateUrl: 'tpl/university/list.html',
                controller: 'UniversityCtrl',
            })
            .state('app.university.create', {
                url: '/criar',
                templateUrl: 'tpl/university/create.html',
                controller: 'UniversityCtrl',            
            })

您可以使用angular toast将其引用到index.html页面,还可以添加css,然后在页面底部配置指令如下:

<toaster-container toaster-options="{
  'closeButton': false,
  'debug': false,
  'position-class': 'toast-top-right',
  'onclick': null,
  'showDuration': '200',
  'hideDuration': '1000',
  'timeOut': '5000',
  'extendedTimeOut': '1000',
  'showEasing': 'swing',
  'hideEasing': 'linear',
  'showMethod': 'fadeIn',
  'hideMethod': 'fadeOut'
}"></toaster-container>

然后将其添加到您的角度模块依赖项中作为"烤面包机"(您已经做得很好了),这样之后您就可以在任何您想要的控制器上注入烤面包机服务,如下所示:

angular.module('myApp').controller('myController', [
    '$scope', 'toaster', function($scope,toaster) {
    toaster.pop('success', 'message', 'some message');
}]);

正如文件所说,你可以使用多种选择:

toaster.pop('success', "title", 'Its address is https://google.com.', 15000, 'trustedHtml', 'goToLink');
toaster.pop('success', "title", '<ul><li>Render html</li></ul>', 5000, 'trustedHtml');
toaster.pop('error', "title", '<ul><li>Render html</li></ul>', null, 'trustedHtml');
toaster.pop('wait', "title", null, null, 'template');
toaster.pop('warning', "title", "myTemplate.html", null, 'template');
toaster.pop('note', "title", "text");

所以看看这个plunkr

我以以下方式使用烤面包机:

在索引html中包含烤面包机:

<script type="text/javascript" src="/vendor/toastr/toastr.min.js"></script>

定义一个可以注入任何控制器的工厂:

angular.module('app').value('ngToastr',toastr);
angular.module('app').factory('ngNotifier',function(ngToastr){
    return{
        notify: function(msg){
            ngToastr.success(msg);
        },
        notifyError: function(msg){
            ngToastr.error(msg);
        },
        notifyInfo: function(msg){
            ngToastr.info(msg);
        }
    }
});

之后,您可以在任何控制器中注入此模块:

angular.module('app').controller('myCtrl',function($scope, ngNotifier) {
    ngNotifier.notifyError($scope.validationError);
});
我喜欢@AndreiC的回答。一年后,我使用了一种更强大的工厂服务:


.factory('notifierService',function(toaster){
    return{
        notify: function(msg){
                toaster.pop('success', 'Update Successful', 'The ' + msg + ' setting was updated');
        },
        notifyError: function(msg){
                toaster.pop('error', 'Something Went Wrong', 'Please check with an administrator');
        },
        notifyInfo: function(msg){
                toaster.pop('info', 'Information', 'The ' + msg + 'just happened' );
        }
    };
})
关于$resource承诺
.$promise.then(function() {
     notifierService.notify('email server');
 });