簡體   English   中英

AngularJS - 自動將數據從一個控制器更新到另一個控制器

[英]AngularJS - Auto update data from one controller to another

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並獲取最新記錄。

添加或刪除新用戶時,如何動態更新用戶列表?

您應該使用$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);
            })
        }
    ]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM