广播和页面加载时的角度运行功能

时间:2014-06-26 00:00:39

标签: javascript jquery angularjs

我有一个如下控制器,在提交表单时通过.$on调用.$broadcast属性。我还希望在控制器加载时运行该事件。有没有一种语法上简单的方法可以做到这一点,还是我必须添加一个on page load监听器?

myApp.controller('DownloadsCloudCtrl', ['$scope', 
                                        '$rootScope', 
                                        'requestService',
  function($scope, $rootScope, requestService){
  $scope.title = 'Most Popular Keywords';
  $scope.tooltip = 'Test tooltip';
  $rootScope.$on('updateDashboard', function(event, month, year) {
    requestService.getP2PKeywordData(month, year).then(function(data) {
      $scope.d3Data = data;
    });
  });
}]);

1 个答案:

答案 0 :(得分:1)

如果你想在你的控制器加载时运行它,那么这非常简单。基本上将$on逻辑删除到自己的函数中并在控制器init中调用它:

myApp.controller('DownloadsCloudCtrl', ['$scope', '$rootScope', 'requestService',
function($scope, $rootScope, requestService){
    $scope.title = 'Most Popular Keywords';
    $scope.tooltip = 'Test tooltip';

    var updateDash = function(month, year) {
        requestService.getP2PKeywordData(month, year).then(function(data) {
            $scope.d3Data = data;
        });
    };

    $rootScope.$on('updateDashboard', function(event, month, year) {
        // run the update function
        updateDash(month, year);
    });

    // run the update function once when the controller loads
    updateDash(someMonth, someYear);
}]);

现在这可以更好地抽象为服务,但这至少应该让你开始。