AngularJS - 自动将数据从一个控制器更新到另一个控制器

时间:2016-12-15 07:56:01

标签: angularjs angularjs-controller

Ctrl 1

$scope.$watch(function () {return svc.getMessage();}, function (messageBody) {
    if(messageBody){

        var eventName = data.eventName;
        var someCtrl = $rootScope.$new();
        $controller('someCtrl', {$scope: someCtrl});

        // For add user event 
        if (eventName == "EVENT_USER_ADDED") {
            someCtrl.addUserEventAction();
        }
    }

    svc.clearMessage();
});

Ctrl 2

$scope.addUserEventAction = function () { 
    var userTreeViewCtrl = $rootScope.$new();
    $controller('userTreeViewCtrl', {
        $scope: userTreeViewCtrl
    });
    userTreeViewCtrl.ReloadUserList();
};

Ctrl 3

$scope.initUserTreeView = function () {
    $scope.treeLength = 0;
    userModuleService.getUserTreeView(usertId, siteId)
    .then(function (data) {
        $scope.tree = data;
        if (data !== undefined) {
            $scope.treeLength = $scope.tree.length;
        } else {
            $scope.treeLength = 0;
        }
    });
};

$scope.initUserTreeView();


$scope.ReloadUserList = function(){
    $scope.initUserTreeView();
};

HTML

<div ng-if="treeLength > 0">
    <div ng-repeat="user in tree">
        <li class="pointer"><a>{{user.name}}</a></li>
    </div>
</div>

从admin添加用户时,应用程序会收到一条事件名称为EVENT_USER_ADDED的弹出消息。基于此,我正在动态更新用户列表html并获取最新记录。

添加或删除新用户时,如何动态更新用户列表?

1 个答案:

答案 0 :(得分:0)

您应该使用$broadcast系统使用AngularJS的常用方法。您的示例无效,因为$controller('userTreeViewCtrl', { ...正在初始化新的控制器实例。它不会初始化HTML视图中使用的控制器。因此,您的视图中绑定的$scopes将不会更新,因为它是另一个实例。

视图

<div ng-controller="TestController">
    <a ng-click="sendData()">Send Data</a>
</div>

<div ng-controller="ListenController">
    <span ng-bind="data"></span>
</div>

控制器

/**
 * Test controller
 */
angular.module('app')
    .controller('TestController', [
        '$scope',
        '$rootScope',
        function ($scope, $rootScope) {
            $scope.sendData = function () {
                $rootScope.$broadcast('myEvent', 'someData')
            };
        }
    ]);

/**
 * Listen controller
 */
angular.module('app')
    .controller('ListenController', [
        '$rootScope',
        function ($rootScope) {

            $scope.data = '';

            $rootScope.$on('myEvent', function (event, data) {
                $scope.data = data;
                alert($scope.data);
            })
        }
    ]);