How to extend parent state controller with onmouseover to child states?

195 views Asked by At

I have a simple angularjs controller which uses jquery that logs something to the console when mouse goes over an anchor element:

app.controller('MenuController', function() {
    $("a").on('mouseover', function (e) {
        console.log("mouser over a link");
    });
});

I am using ui-router for organizing my app states:

app.config(["$urlRouterProvider", "$stateProvider", function($urlRouterProvider, $stateProvider) {

    // For any unmatched url, redirect
    $urlRouterProvider
        .otherwise("/");

    $stateProvider
        .state('menu', {
            controller: "MenuController",
            controllerAs: "menuCtrl",
            templateUrl: "partials/menu.html"
        })
            .state('menu.menu', {
                url: '/',
                templateUrl: "partials/menu.menu.html"
            })
            .state('menu.difficulty', {
                url: '/difficulty',
                templateUrl: "partials/menu.difficulty.html",
                controller: "DifficultyController",
                controllerAs: "difCtrl"
            })
            .state('menu.settings', {
                url: "/settings",
                templateUrl: "partials/menu.settings.html"
            })
}]);

My basic html for the menu is in the menu.html file:

<!-- view - menu -->
<div ui-view>
    <!-- nested views -->
</div>

Inside here a bunch of nested views get inserted through states. These views have a lot of anchor elements yet nothing happens when mouse goes over them. Why is that so? Shouldn't parent state controller expand on to child states? Thanks for the help!

1

There are 1 answers

2
Mohit On

The data which is bound to $scope in parent controller is accessible in the child states because the parent controller always runs if we access the child state. In Menu Controller,If write write

$scope.name = 'XYZ'

This $scope.name is accessible in every child controller using $scope.name.

EDIT: In your MenuController bind this anchor on document like this and It will work

app.controller('MenuController', function() {
  $(document).on('mouseover','a', function (e) {
    console.log("mouser over a link");
  });
});