Search code examples
javascripthtmlangularjsmonaca

angularjs call another controller's function


I have a ons-list with the following ons-items :

<ons-list-item style="font-family:roboto;font-size:17px" ng-class="{'selected-menu':selectedRow==0,'no-selected':selectedRow!=0}"
        modifier="tappable" class="list__item__line-height"
        onclick="app.slidingMenu.setMainPage('principal.html', {closeMenu: true})"
        ng-click="principal(0)">
        <i class="fa fa-home fa-lg"></i>
        &nbsp;Principal
</ons-list-item>

<ons-list-item style="font-family:roboto;font-size:17px" ng-class="{'selected-menu':selectedRow==1,'no-selected':selectedRow!=1}"
        modifier="tappable" class="list__item__line-height"
        onclick="app.navi.pushPage('ingreso.html', { animation : 'slide' } );app.slidingMenu.closeMenu()"
        ng-click="principal(1)">
        <i class="fa fa-car fa-md"></i>
        &nbsp;Nuevo Registro
</ons-list-item>

etc...

and I have a function called principal() that what it does is change the "$scope.selectedRow" so the item changes classes. I need to access that function so i can change the class from another controller, i've check some answers from other questions but I haven't been able to do it right, is there a way to acomplish this?

this is my principal() function:

$scope.principal = function(item){
    $scope.selectedRow = item;
}

Solution

  • As suggested by SSH i ended up using broadcast and on so the credit goes to him, what I did was:

    declare my controller like:

    module.controller('Ingreso', ['$scope','$rootScope',function($scope,$rootScope){
    

    inside of it a broadcast the event:

    $rootScope.$broadcast("ingresing");
    

    and from the menu controller(same declaration):

    module.controller('Principal', ['$scope','$rootScope', function($scope,$rootScope) {
    

    and listen to the briadcasted event:

    $rootScope.$on("ingresing", function(){
        $scope.selectedRow = 1;
    }); 
    

    Thank you very much for the help!