dease
dease

Reputation: 3076

Global event handler in Angular

I am not sure how should I handle event in my angular app.

I am setting some $rootScope property in my .run() function:

.run(['$rootScope', '$state', '$stateParams', '$location',
    function($rootScope, $state, $stateParams, $location) {
        $rootScope.something = "something_";
    }
]);

My HTML looks like:

  <body class="dashboard" ng-app="app">

      <select name="active_project" id="active_project">
          <option value=""></option>
      </select>    
    <div id="content" ui-view></div>


  </body>

Now - when user changes the dropdown value (active_project) I want to change $rootScope.something value to new one.

How should I do such thing?

EDIT: I don't want to make it in single controller. As you can see, this dropdown is OUTSIDE ui-view. So handler should be somewhere outside the controller. If not, I will be forced to handle this change in every single controller across the app.

Upvotes: 0

Views: 639

Answers (2)

michelem
michelem

Reputation: 14590

You can use ng-selected with a function assigning the select ng-model to the $rootScope:

JSFiddle

HTML:

<div ng-app="app" ng-controller="dummy">
    <select name="active_project" ng-selected="selectIt()" ng-model="somethingFromSelect" id="active_project">
          <option value="hello">hello</option>
          <option value="world">world</option>
    </select>
    {{something}}
</div>

JS:

var app = angular.module("app", []);
app.run(['$rootScope', '$location',
    function($rootScope, $location) {
        $rootScope.something = "";
    }
]);
app.controller('dummy', ['$rootScope', '$scope', function ($rootScope, $scope) {
    $scope.selectIt = function () {
        $rootScope.something = $scope.somethingFromSelect;
    };
}]);

Upvotes: 0

chandings
chandings

Reputation: 549

Basically you need to write a ng-change to update on change. your html will become:

  <body class="dashboard" ng-app="app" ng-controller='myController'>

      <select ng-change='selectChanged()' ng-model='myModel' name="active_project" id="active_project">
          <option value=""></option>
      </select>    
    <div id="content" ui-view></div>


  </body>

You will also need to define a controller to listen to that change:

app.controller('myController', ['$scope', '$rootScope', function(scope, rootScope){
    scope.selectChanged = function(){
        rootScope.something = scope.myModel;
        alert(rootScope.something);
    }
}]);

I have also added a link to a functioning fiddle.

After having given you the solution, I would like to add it is not a good idea to have value in rootscope. If you post what you are trying to achieve may be somebody here can guide you better.

Hope this helps.

Upvotes: 1

Related Questions