【问题标题】:How to $rootScope.$broadcast from services in angular.js如何从 angular.js 中的服务 $rootScope.$broadcast
【发布时间】:2016-01-15 15:17:16
【问题描述】:

如何从 angular.js 中的服务 $rootScope.$broadcast

在 $rootScope.$broadcast 之后,我想从控制器访问 console.log(data),但我在控制台中看不到任何内容

我的代码:

'use strict';

angular.module('adf.widget.charts')
   .factory('chartService', function ($q, $rootScope){
    return {
      getSpreadsheet: function init(path){
        var deferred = $q.defer();
        Tabletop.init({
          key: path,
          callback: function(data, Tabletop) {
             $rootScope.$broadcast(data)
      },
          simpleSheet: true,
          debug: true
        });
      }
    }

  })


  .controller('piechartCtrl', ['$scope', 'chartService', function($scope, chartService, urls) {
    $scope.$on('getSpreadsheet', function(data){
      console.log(data)
    });

  }]);

【问题讨论】:

  • 阅读$broadcast的文档

标签: javascript jquery angularjs


【解决方案1】:

$rootScope.$broadcast 应该有第一个参数是事件名称,然后您可以将数据作为第二个参数传递给该事件。

$rootScope.$broadcast('getSpreadsheet', data)

【讨论】:

    【解决方案2】:

    这是$broadcast 语法:

    $broadcast(name, args);
    

    name 参数表示应该在子范围行中触发的事件的名称。

    例子:

    $broadcast('testEvent', 'test data');
    
    $on('testEvent', function(arg){
       console.log(arg);   //This will log 'test data'
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      • 2018-03-16
      • 2014-12-30
      • 2016-06-09
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      相关资源
      最近更新 更多