Angularjs $rootScope.$broadcast不工作

Angularjs $rootScope.$broadcast不工作,angularjs,angularjs-directive,angular-broadcast,Angularjs,Angularjs Directive,Angular Broadcast,我正在尝试获取$rootScope.$broadcast以刷新我的视图。 该项服务是— var app = angular.module("productsApp", []) .service("serviceProvider", function ($http) { this.getDatas = function getDatas(data) { return $http({ method: 'POST', ur

我正在尝试获取$rootScope.$broadcast以刷新我的视图。 该项服务是—

var app = angular.module("productsApp", [])
    .service("serviceProvider", function ($http) {
        this.getDatas = function getDatas(data) {
            return $http({
                method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
                    'Authorization': apiKey
                },
                data: data
            })
        }
        return this
    }).factory("sharedService", function ($rootScope) {

        var mySharedService = {};

        mySharedService.values = [];

        mySharedService.passData = function (newData) {
            mySharedService.values = newData;
            $rootScope.$broadcast('dataPassed', newData);
        }

        return mySharedService;
    });
通过控制器调用-

function searchProductsController($scope, $window, serviceProvider, sharedService) {
    $scope.submit = function () {
        var data = { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
        serviceProvider.getDatas(data).then(function (response) {
            var result = response;
            sharedService.passData(result.data.data);
        });
    }
};
在这个控制器
sharedService.passData
中,它将新数组传递给服务方法。然后,它尝试使用行-
$rootScope.$broadcast('dataPassed',newData)

我不知道为什么它不广播对视图的更改。有没有其他方式来广播这些变化

注意- 我先前的问题帮不了我什么忙

编辑

到目前为止,我的听众已经改变了-

mySharedService.passData = function (newData) {
    $rootScope.$broadcast('dataPassed', newData)
}
$rootScope.$on('dataPassed', function (newData) {
    mySharedService.values = newData;
})

但仍无法刷新视图。

您应该收听正在播放的内容:

$rootScope.$on('dataPassed', function(data){
console.log(data);
});

使用$broadcast或$emit时,此参考可能会有所帮助:

。您应该启用$scope.$来收听该事件

$scope.$on('dataPassed', function(){ //code go here });
编辑:更新问题要求的工作代码

var app = angular.module("productsApp", [])
    .service("serviceProvider", function ($http) {
        this.getDatas = function getDatas(data) {
            return $http({
                method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
                    'Authorization': apiKey
                },
                data: data
            });
        }
        return this
    }).factory("sharedService", ['$rootScope', function ($rootScope) {
        var mySharedService = {
            values: [],
            setValues: function(data){
                if(data){
                    mySharedService.values.length = 0;
                    data.forEach(function(item){
                        mySharedService.values.push(item);
                    });    
                }
            }
        };
        return mySharedService;
    }]);      
function GetController($scope, serviceProvider, sharedService, $rootScope) {
    var shareData = sharedService;
    $scope.products = sharedService.values;
    $scope.shareData = sharedService;
    var data = { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
    serviceProvider.getDatas(data).then(function (response) {
        sharedService.setValues(response.data.data);
    });
}
function searchProductsController($scope, $window, serviceProvider, sharedService, $rootScope) {
    $scope.submit = function () {
        var data = { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
        serviceProvider.getDatas(data).then(function (response) {
            sharedService.setValues(response.data.data);
        });
    }
};

你应该安排一个听众来听broadbasted事件。广播事件不会直接在视图html上更新视图数据。您必须在作用域上使用
$on
来绑定作用域上的事件。在它的回调函数中。您将获得一个好处,即获取广播数据并再次将检索数据重新分配给scope变量以获得更新的绑定

代码

var app = angular.module("productsApp", [])
  .service("serviceProvider", function($http) {
  this.getDatas = function getDatas(data) {
    return $http({
      method: 'POST',
      url: serviceUrl + '/GetProductsByCategoryOrName',
      headers: {
        'Authorization': apiKey
      },
      data: data
    })
  }
  return this;
}).factory("sharedService", ['$rootScope', function($rootScope) {

  var mySharedService = {};

  mySharedService.values = [];

  mySharedService.passData = function(newData) {
    mySharedService.values = newData;
    $rootScope.$broadcast('dataPassed', newData)
  }

  return mySharedService;
}]);

function GetController($scope, serviceProvider, sharedService, $rootScope) {
  var data = {
    "query": "grocery",
    "categoryId": "976759",
    "pageIndex": 0,
    "sortDirection": "asc"
  };
  serviceProvider.getDatas(data).then(function(response) {
    sharedService.passData(response.data.data);
  });
  //listener should register when controller loads
  $scope.$on('dataPassed', function(event, newData) {
    sharedService.values = newData;
    $scope.products = sharedService.values;
  })
}

function searchProductsController($scope, $window, serviceProvider, sharedService, $rootScope) {
    $scope.submit = function() {
      var data = {
        "query": $scope.searchText,
        "categoryId": "976759",
        "pageIndex": 0,
        "sortDirection": "asc"
      };
      serviceProvider.getDatas(data).then(function(response) {
        var result = response;
        sharedService.passData(result.data.data);
      });
    }
    //listener should register when controller loads
    $scope.$on('dataPassed', function(event, newData) {
      console.log(newData);
      sharedService.values = newData;
    })
};

@Manoz至于你之前的回答,我也已经给了你答案。我也为此更新了plunker。至于使用
$rootscope.
,您有两个参数,其中一个是event,另一个是您正在广播的数据。我在两个答案中模拟了您的api调用,以使您更加理解

下面是plunker使用的
$rootscope


角度控制器
AngularJS示例应用程序
输入搜索id
{{product.name}
var-app=angular.module('app',[]);
app.run(['$rootScope',函数($rootScope){
$rootScope.test=123;
}]);
应用程序工厂(“服务”,功能($rootScope){
函数passData(newData){
警惕(“我在这里”);
$rootScope.$broadcast('dataPassed',newData);
}
返回{
passData:passData
}
}).factory(“dataService”,函数($http){//mock,用于从api获取值
返回{
getComments:函数(roomid){
if(roomid==1){
var数据=[{“名称”:“亚历克斯”,“地点”:“加德满都”},{“名称”:“上帝”,“地点”:“西雅图”}];
返回数据;
}
if(roomid==2)
{
var newdata=[{“名称”:“新名称”,“地点”:“加德满都”},{“名称”:“新名称2”,“地点”:“西雅图”}];
返回新数据;
}
}
}
});
app.controller('searchProductsController',函数($scope,Service,$http,dataService){
$scope.setPlace=函数(searchText){
var newdata=dataService.getComments(searchText);
服务.passData(newdata);
}
})
.controller('GetController',函数($scope,Service,$rootScope){
$rootScope.$on('dataPassed',函数(事件,参数){
$scope.products=args;
})
})

您犯了一个非常小但非常有效的错误。从以下位置更改您的侦听器:

$rootScope.$on('dataPassed', function (newData) {
    mySharedService.values = newData;
});
为此:

$rootScope.$on('dataPassed', function ($event, newData) {
    mySharedService.values = newData;
});
在任何已调度的AngularJS范围事件上,每个侦听器的第一个参数都是一个$event对象


我很惊讶有一个老问题,有这么多答案,却没有注意到真正的问题。

你的
$scpe.$on
?@Artless,我该如何使用它?$broadcast不会直接在视图上异步数据…你需要使用$on设置listner over broadcasted事件,然后你可以在它的回调函数中获得broadcasted数据。并重新分配数据以反映其范围。@PankajParkar,我尝试了下面两种答案,但都不适用于我。恐怕我在这方面做错了什么。请您协助我以下解决方案应该有效…如果您没有做错什么…请添加plunkr我如何访问服务中的$scope?不,您不应该。。上面的代码你应该放在一个控制器里你可以在stackoverflow上查看我的js群组聊天吗?我还没有得到这份工作
$rootScope.$on('dataPassed', function ($event, newData) {
    mySharedService.values = newData;
});