0

I need to call a function from another controller in Angular JS. Another question on Stack Overflow suggests to use a service instead: https://stackoverflow.com/a/11847277/1910735

JSFiddle: http://jsfiddle.net/0z7ux66c/

So I created a service, and two controllers:

    var app = angular.module("myApp", []);

    app.factory('trackingService', function ($rootScope) {

        var trackingInstance = {};

        trackingInstance.assetInformationModel = null;

        trackingInstance.RefreshDashboard = function () {
            $rootScope.$broadcast('Refresh');
        };

        return trackingInstance;
    });

    app.controller('assetInformationController', function ($scope,  trackingService) {
        $scope.UpdateDashboard = function () {
            console.log('UpdateDashboard()')
            trackingService.RefreshDashboard();
        };

        $scope.$on('Refresh', function () {

// THIS gets called
            console.log('Refresh');
        });


    });

    app.controller('liveTrackingController', function ($scope,  trackingService){
        $scope.$on('Refresh', function () {

// THIS doesn't
            console.log('Refresh in liveTrackingController');
        });


    });

From the code, it should display the following three lines in Console:

UpdateDashboard()
Refresh
Refresh in liveTrackingController

But it is not calling the Reresh Event from liveTrackingController - It is only displaying:

UpdateDashboard()
Refresh

1 Answer 1

1

In your jsfiddle, the liveTrackingController is not being used anywhere.

Add something like this into your html to get the desired log output.

<div ng-controller="liveTrackingController"></div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.