在状态变化时触发Angular Material toast

时间:2015-11-05 14:57:51

标签: angularjs angular-ui-router angular-material angular-services

我目前正在开发一个AngularJS网络应用程序,该应用程序已设置并使用Angular Material

我已经实现了Angular Material Toast功能,没有任何问题。

另外,我使用ui-router设置了几个视图 - 1.索引,2。父级& 3.孩子(见附件)。

我可以查看并点击Prev / Next状态:

#/dashboard/raiding-the-rails/1

那么问题是什么?好吧,我希望能够根据当前状态ID触发特定的Toast消息。

例如#/dashboard/raiding-the-rails/5将显示土司留言5。

我尝试过建立一个服务/工厂而无法弄清楚这是怎么回事!

我甚至订阅egghead.io只是为了尝试寻找专业解决方案!

任何帮助和建议都会有所帮助!
谢谢!!!

图表:

Screenshot

应用

(function(angular, undefined){
  "use strict";
  var am = angular.module('virtual-fitting', ['ngAnimate', 'ngAria', 'ngMaterial', 'ui.router', 'firebase']);
  // Beginning
  am.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
      .state('authentication', {
        url: '/authentication',
        templateUrl: '../views/authentication.html'
      })
      .state('dashboard', {
        url: '/dashboard',
        controller: 'dashboardCtrl as dashboard',
        templateUrl: '../views/dashboard.html'
      })
      .state('dashboard.bodytype', {
        url: '/body-type',
        templateUrl: '../views/dashboard.body-type.html'
      })
      .state('dashboard.raidingtherails', {
        abstract: true,
        url: '/raiding-the-rails',
        templateUrl: '../views/dashboard.raiding-the-rails.html'
      })
      .state('dashboard.raidingtherails.dress', {
        url: '/:id',
        controller: 'raidingtherailsCtrl as raiding',
        templateUrl: '../views/dashboard.raiding-the-rails.dress.html'
      })
      .state('dashboard.collection', {
        url: '/collection',
        templateUrl: '../views/dashboard.collection.html'
      })
      .state('dashboard.lovelist', {
        url: '/love-list',
        templateUrl: '../views/dashboard.love-list.html'
      })
      .state('dashboard.secondopinion', {
        url: '/second-opinion',
        templateUrl: '../views/dashboard.second-opinion.html'
      });
      $urlRouterProvider.otherwise('/dashboard/raiding-the-rails/1');
  });
  // End
})(angular);


主要控制器:

(function(angular, undefined) {
  "use strict";
  var am = angular.module('virtual-fitting');
  // Beginning
  am.controller('dashboardCtrl', function($scope, $state, $mdDialog, $mdToast) {
    var self = this;
    // FAB Speed Dial
    self.isOpen = false;
    self.selectedMode = 'md-scale';
    self.selectedDirection = 'down';
    // onClick State
    self.pageUrl = function(state) {
      $state.go(state);
    };
    // Dialog Show
    self.dialog = function($event, id) {
      $mdDialog.show({
        clickOutsideToClose: true,
        controller: function($mdDialog) {
          this.item = id;
          // Dialog Hide
          this.close = function() {
            $mdDialog.cancel();
          };
          this.submit = function() {
            $mdDialog.hide();
          };
        },
        controllerAs: 'dialog',
        templateUrl: '../views/dashboard.dialog.html',
        targetEvent: $event
      });
    };
    // Toast Setup
    self.toastPosition = angular.extend({}, {
      bottom: true,
      left: true
    });
    self.getToastPosition = function() {
      return Object.keys(self.toastPosition)
        .filter(function(pos) {
          return self.toastPosition[pos];
        })
        .join(' ');
    };
    // Toast Show
    self.showToast = function() {
      $mdToast.show({
        controller: function() {
          this.item = 'Hello';
          // Toast Hide
          this.hideToast = function() {
            $mdToast.hide();
          };
        },
        controllerAs: 'toast',
        templateUrl: '../views/dashboard.toast.html',
        hideDelay: 10000,
        position: self.getToastPosition()
      });
    };
  });
  // End
})(angular);

儿童控制器:

(function(angular, undefined) {
  "use strict";
  var am = angular.module('virtual-fitting');
  // Beginning
  am.controller('raidingtherailsCtrl', function($scope, $state, $stateParams) {
    var self = this;
    self.id = $stateParams.id;
    self.prev = function() {
      self.minus = parseFloat(self.id) - parseFloat(1);
      $state.go('dashboard.raidingtherails.dress', {'id': self.minus});
    };
    self.next = function() {
      self.plus = parseFloat(self.id) + parseFloat(1);
      $state.go('dashboard.raidingtherails.dress', {'id': self.plus});
    };
  });
  // End
})(angular);


服务(已删除):

(function(angular, undefined) {
  "use strict";
  var am = angular.module('virtual-fitting');
  // Beginning
  am.service('', function() {});
  // End
})(angular);

更新

我尝试使用以下内容,但正如您所看到的那样,console.log正在输出之前的id而不是正确的&当前身份证。现在我只需要触发分配给状态id的消息!任何想法?

$rootScope.$on('$stateChangeStart',
  function(event, toState, toParams, fromState, fromParams){
    var test = $state.params.id;
    console.log(test);
  });

enter image description here

更新
在进一步搜索并重写上述内容之后,我终于设法获得了当前的状态ID。

$rootScope.$watchCollection(function(){
  return $state.params;
}, function(){
    console.log($state.params.id);
});

enter image description here应答

// Toast Setup
    self.toastPosition = angular.extend({}, {
      bottom: true,
      left: true
    });
    self.getToastPosition = function() {
      return Object.keys(self.toastPosition)
      .filter(function(pos) {
        return self.toastPosition[pos];
      }).join(' ');
    };
    $rootScope.$watchCollection(function(){
      return $state.params;
    }, function(){
      // State ID (State Params)
      var stateID = $state.params.id;
      // Toast Messages
      var toastMessages = {
        "results": [
          {'id': '1', 'message':'Textured fabrics are what you want to look for, this will help.'},
          {'id': '2', 'message':'This dress is perfect for a Triangle body shape like yours, Kerry! Its a beautiful style too!'},
          {'id': '3', 'message':'Just click on a designers name to view their collection - We have some amazing dresses!'}
        ]
      };
      // Filter against State ID
      var toastMessage = $filter('filter')(toastMessages.results, {id: stateID})[0];
      // Prevent Undefined ID
      if(toastMessage){
        self.messageID = toastMessage.id;
      }
      // Check State ID against Message ID
      if(stateID === self.messageID) {
        // Show Toast
        $mdToast.show({
          controller: function() {
            this.item = toastMessage.message;
            // Hide Toast
            this.hideToast = function() {
              $mdToast.hide();
            };
          },
          controllerAs: 'toast',
          templateUrl: '../views/dashboard.toast.html',
          hideDelay: 10000,
          position: self.getToastPosition()
        });
      } else {
        // Hide Toast on 'IF' Fail
        $mdToast.hide();
      }
    });

2 个答案:

答案 0 :(得分:0)

来自https://github.com/angular-ui/ui-router/wiki#state-change-events

$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams){ ... })

让您跟踪更改状态的时间。您可能希望在制作/配置模块后立即将其放入主控制器或.run()

在设置状态时,可以添加包含可放置任意数据的对象的data属性。作为一个例子,我建议您保留要在祝酒词中显示的字符串:

.state('dashboard.raidingtherails', {
    abstract: true,
    url: '/raiding-the-rails',
    templateUrl: '../views/dashboard.raiding-the-rails.html',
    data: {
        toast: "Raiding the rails toast"
    }
})

然后在你的onStateChangeStart中你可以引用toState.data.toast。如果您这样做,您将不再需要服务/提供商,但如果您想要更高级的功能,您可能会决定制作一个。

此外,您可以使用ui-router的网址参数获取网址参数(/5和网址末尾)。

答案 1 :(得分:0)

// Toast Setup
    self.toastPosition = angular.extend({}, {
      bottom: true,
      left: true
    });
    self.getToastPosition = function() {
      return Object.keys(self.toastPosition)
      .filter(function(pos) {
        return self.toastPosition[pos];
      }).join(' ');
    };
    $rootScope.$watchCollection(function(){
      return $state.params;
    }, function(){
      // State ID (State Params)
      var stateID = $state.params.id;
      // Toast Messages
      var toastMessages = {
        "results": [
          {'id': '1', 'message':'Textured fabrics are what you want to look for, this will help.'},
          {'id': '2', 'message':'This dress is perfect for a Triangle body shape like yours, Kerry! Its a beautiful style too!'},
          {'id': '3', 'message':'Just click on a designers name to view their collection - We have some amazing dresses!'}
        ]
      };
      // Filter against State ID
      var toastMessage = $filter('filter')(toastMessages.results, {id: stateID})[0];
      // Prevent Undefined ID
      if(toastMessage){
        self.messageID = toastMessage.id;
      }
      // Check State ID against Message ID
      if(stateID === self.messageID) {
        // Show Toast
        $mdToast.show({
          controller: function() {
            this.item = toastMessage.message;
            // Hide Toast
            this.hideToast = function() {
              $mdToast.hide();
            };
          },
          controllerAs: 'toast',
          templateUrl: '../views/dashboard.toast.html',
          hideDelay: 10000,
          position: self.getToastPosition()
        });
      } else {
        // Hide Toast on 'IF' Fail
        $mdToast.hide();
      }
    });