Multiple angularjs controllers using ngstomp on the same page

I am using ngStomp to wire websocket subscriptions to angularjs controllers. When I have one controller on a page by itself it works fine. When I add another controller in an earlier div it stops working.

Is this because it's trying to connect stomp twice to the same endpoint?

My controller declarations are:

var market = 'all';
var orderApp = angular.module('openOrderApp', ['ngStomp']); 
orderApp.controller('openOrderController', function ($stomp, $scope) {
    $stomp.connect('https://localhost/marketdata-websocket', {})
        .then(function (frame) {
            console.log('Subscribing to /topic/openOrders');
            var subscription = $stomp.subscribe('/topic/openOrders', 
                function (payload, headers, res) {
                        $scope.exchanges = payload;
                        $scope.$apply($scope.orders);
                });
            $stomp.send("/app/openOrders", market);
     });
});

and

var market = 'all';
var statusApp = angular.module('statusApp', ['ngStomp']); 
statusApp.controller('statusController', function ($stomp, $scope) {
    $stomp.connect('https://localhost/marketdata-websocket', {})
        .then(function (frame) {
            console.log('Subscribing to /topic/exchangeStatus');
            var subscription = $stomp.subscribe('/topic/exchangeStatus', 
                function (payload, headers, res) {
                        $scope.exchanges = payload;
                        $scope.$apply($scope.exchanges);
                });
            $stomp.send("/app/exchangeStatus", market);
     });
});

and in one div there is:

<div class="openOrders row" ng-app="openOrderApp" ng-controller="openOrderController">

followed by:

<div class="exchangeStatus row" ng-app="statusApp" ng-controller="statusController">

When I remove the open orders div the status controller works ok.

1 answer

  • answered 2017-06-17 19:57 glynbach

    After reading the angularjs docs rather than carrying on winging it :P

    Cannot have two ng-apps declared on a page. Can obviously have multiple controllers. There's obviously many ways to structure this but I ended up by applying the two controllers to a module.

    var app = angular.module('app', ['ngStomp']); 
    var controllers = {};
    controllers.OpenOrderController = function ($stomp, $scope) {
        console.log("Creating order controller");
        etc...
    };
    controllers.ExchangeController = function ($stomp, $scope) {
        console.log("Creating exchange controller");
        etc...
    };
    app.controller(controllers);
    

    And then in the html tag

    <html ng-app>
    

    And the controllers in the divs:

    <div ng-controller="OpenOrderController">
    
    <div ng-controller="ExchangeController">