Angular Js newbie - link in a controller view that triggers another controller action

前端 未结 2 593
失恋的感觉
失恋的感觉 2020-12-12 04:33

angular newbie here.

Let\'s say I have an application that needs to monitor different things like \"news submitted\" \"login attemps\" and so on. My mainController w

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 05:04

    This is how it would work -

    1. from your mainController, emit an event upwards (through $emit). Call to $emit dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners.

    2. Inside newsController and loginAttemptsController add an event listener (using $rootScope.$on) to listen to the event emitted from mainController, get data from the target scope (in your case its mainController's scope) and set it to newsController and loginAttemptsController's scope model.

    for details go through angular documentation - https://docs.angularjs.org/api/ng/type/$rootScope.Scope

    I have set up a plunk here - http://plnkr.co/edit/1dhdPfmB1WwAkYhsz4Hv

    Example code (html template) :

    {{newsControllerData.News}}
    {{loginAttemptsControllerData.loginAttempts}}

    Example code (main controller) :

    app.controller("mainController", ["$rootScope", "$scope", function ($rootScope, $scope) {
    
        $scope.newsControllerData = {};
        $scope.loginAttemptsControllerData = {};
    
        // from mainController emit HandleNews upwards on the scope
        $scope.OnNewButtonClick = function () {
            $scope.newsControllerData.info = "Hello World";
            $scope.$emit("HandleNews");
        }
    
        // from mainController emit HandleLoginAttempts upwards on the scope
        $scope.OnLoginAttemptButtonClick = function () {
            $scope.loginAttemptsControllerData.info = "login count = 4";
            $scope.$emit("HandleLoginAttempts");
        }
    
    }]);
    

    Example code (news Controller) :

    app.controller("newsController", ["$rootScope", "$scope", function ($rootScope, $scope) {
    
        $scope.newsControllerData = {};
    
        // when any controller calls HandleNews, i would listen
        $rootScope.$on("HandleNews", function (evt, next, current) {
            $scope.newsControllerData.News = evt.targetScope.newsControllerData.info;
        });
    
    }]);
    

    Example code (loginAttempts Controller) :

    app.controller("loginAttemptsController", ["$rootScope", "$scope", function ($rootScope, $scope) {
    
        $scope.loginAttemptsControllerData = {};
    
        // when any controller calls HandleLoginAttempts, i would listen
        $rootScope.$on("HandleLoginAttempts", function (evt, next, current) {
            $scope.loginAttemptsControllerData.loginAttempts = evt.targetScope.loginAttemptsControllerData.info;
    
        });
    
    
    }]);
    

提交回复
热议问题