使用AngularJS中的$ broadcast自动更新两个控制器中的id变量

问题描述 投票:0回答:2
$ctrl.clicker = function(id)
{
   $rootScope.$broadcast('idBull', id);
}

当我鼠标输入图像时,上面的函数被调用。我想在另一个控制器中共享id并广播对此id所做的任何更改。

$scope.$on('idBull', function (event, data) {
  console.log(data); // 'Data to send'
});

在另一个控制器中,我使用代码来执行我的id控制台,但没有得到任何结果。

angularjs broadcast
2个回答
0
投票

http://jsfiddle.net/87rLob9x/检查这个小提琴希望它有助于HTML

<html ng-app="myApp">
<div ng-controller='ControllerA'>

    <button ng-click='add()'>Add</button
</div>
<div ng-controller='ControllerB'>
    {{ increment }}

</div>

</html>

JS:

var app = angular.module('myApp', [])
.controller('ControllerA', function($scope) {
    $scope.increment = 0;
    $scope.add = function() {
        $scope.$broadcast('hasIncremented');
    }

}).
controller('ControllerB', function($scope) {
    $scope.$on('hasIncremented', function(event) {
        $scope.increment++; 
    });
})

0
投票

不确定为什么你没有让你的代码工作,也许在执行$scope.$on时没有创建/加载带$rootScope.$broadcast的控制器?

另一种解决方案是使用您注入两个控制器的服务,并将其用于通信。广播解决方案示例:

var app = angular.module("app", [])
.controller("ControllerA", function($scope, $rootScope)
{
    $scope.clicker = function(id)
    {
        $rootScope.$broadcast("id changed", id);
    }
})
.controller("ControllerB", function($scope)
{
    $scope.$on("id changed", function(event, id)
    {
        // Do whatever you need to do with id
    });
});

自定义服务的解决方案示例:

var app = angular.module("app", [])
.factory("customService", function()
{
    var callbacks = [];

    return {
        onIdChange: function(callback)
        {
            callbacks.push(callback);
        },
        idChanged: function(id)
        {
            callbacks.forEach(function(callback)
            {
                callback(id);
            });
        }
    };
})
.controller("ControllerA", function($scope, customService)
{
    $scope.clicker = function(id)
    {
        customService.idChanged(id);
    }
})
.controller("ControllerB", function(customService)
{
    customService.onIdChange(function(id)
    {
        // Do whatever you need to do with id
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.