AngularJS: How can I pass variables between controllers?

后端 未结 16 2584
误落风尘
误落风尘 2020-11-22 00:31

I have two Angular controllers:

function Ctrl1($scope) {
    $scope.prop1 = \"First\";
}

function Ctrl2($scope) {
    $scope.prop2 = \"Second\";
    $scope.         


        
16条回答
  •  孤独总比滥情好
    2020-11-22 01:00

    I looked thru the answers above, I recommend pejman's Dec 29 '16 at 13:31 suggestion but he/she has not left a full answer. Here it is, I will put this as --> (you need a service and a listener $watch on one of the scopes from controllers for changes in the service area)

    var app = 
    angular.module('myApp', ['ngRoute', 'ngSanitize']);
    
    app.service('bridgeService', function () {
        var msg = ""; 
        return msg;
    });
    app.controller('CTRL_1'
    , function ($scope, $http, bridgeService) 
    {
        $http.get(_restApi, config)
        .success(
        function (serverdata, status, config) {
            $scope.scope1Box = bridgeService.msg = serverdata;
        });
    });
    app.controller('CTRL_2'
    , function ($scope, $http, bridgeService) 
    {
        $scope.$watch( function () {
            return (bridgeService.msg);
        }, function (newVal, oldVal) {
            $scope.scope2Box = newVal;
        }, true
        );
    });
    

提交回复
热议问题