使用广播angularjs指令通信的指令

时间:2016-08-10 23:20:18

标签: angularjs angularjs-directive angular-directive angularjs-events

我有两个指令,需要在post请求之后将值从一个指令传递到另一个指令。

第一个指令看起来像

var fileUpload = angular.module('fileUploadDirective',[]);
fileUpload.directive('fileUpload', function () {
        return {
            restrict: 'EA',
            templateUrl: 'app/views/fileUpload/file-upload.tpl.html',
            controller: fileUploadCtrl
        }
    });
fileUploadCtrl.$inject = ['$scope', '$rootScope', '$http','FileUploader'];
function fileUploadCtrl($scope, $rootScope, $http, FileUploader) {

    var vm =this
    vm.uploader.onBeforeUploadItem = function (item) {            
        $rootScope.$broadcast("NEW_EVENT",data); //send event
    }
}

第二条指令看起来像

var resultPage = angular.module('resultPageDirective',[]);
resultPage.directive('resultDirective',function(){
    return {
        restrict: 'EA',
        scope: {},
        replace: true,
        link: function($scope, element, attributes){
        },
        controller: function($scope,$rootScope,$attrs,$http){    
            $scope.junkFiles = ["abc","xyz"];
            $scope.$on("NEW_EVENT",function(event,data){ //listen to event
                   console.log(data);
            });

        },
        templateUrl: 'app/views/resultPage/resultPage.tpl.html'
    }
});

未收听第二个指令事件

1 个答案:

答案 0 :(得分:0)

要听取$ scope的事件,您应该使用$on而不是on

$scope.$on("NEW_EVENT",function(event,data){ //listen to event
       console.log(data);
});