如何使用$ broadcast发送对象?

30 angularjs

我有以下内容:

$scope.$watch('tableForm.$pristine', function (newValue) {
    $rootScope.$broadcast("tableDataUpdated", 
        { state: $scope.tableForm.$pristine });
});
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

$scope.$watch('tableForm.$pristine', function (newValue) {
    var tableForm = { pristine: $scope.tableForm.$pristine };
    $rootScope.$broadcast("tableDataUpdated", tableForm);
});
Run Code Online (Sandbox Code Playgroud)

当tableForm $pristine状态更改时,将值$scope.tableForm.$pristine 设置为,False并且广播此消息.

但是,当我尝试接收消息时,未定义"state"的值:

$rootScope.$on("tableDataUpdated", function (args) {
    alert(args.state);
});
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

$rootScope.$on("tableDataUpdated", function (args) {
    alert(args.tableForm);
});
Run Code Online (Sandbox Code Playgroud)

我似乎仍然无法发送对象并收到它

Wal*_*ron 57

那是因为监听器函数有两个参数传递给它event,和args.请参阅角度文档.

尝试:

$rootScope.$on("tableDataUpdated", function (event, args) {
        alert(args.state);
    });