Anonymous Dodo
Anonymous Dodo

Reputation: 271

How to watch variables in other controllers AngularJS

I have a component called histogram demo in which there is a separate controller that has a variable called $scope.selectedElements and I want to watch this variable in the main appCtrl controller. How would I be able to access this variable without $rootScope.

Main HTML

<html lang="en-US" ng-app="histogram-test" ng-controller="appCtrl">

 <div  class="histogram-container"> <histogram-demo options = "options" data="data"></histogram-demo></div>
 </html>

App.JS

angular
.module('histogram-test')
.config(function ($httpProvider, usSpinnerConfigProvider) {
    $httpProvider.defaults.withCredentials = true;
    usSpinnerConfigProvider.setDefaults({
        // see http://spin.js.org/
        color: 'white',
        radius: 30,
        width: 8,
        length: 16,
        shadow: true,
    });
})
.controller('appCtrl', function ($scope, appConfig, $rootScope, auth, $state) {
/** HERE is where I want to watch $scope.selectedElements in Component.js **/}

Component.JS

angular
.module('histogram-test').component('histogramDemo', {
    bindings: {
        data: "=",
        options: "=",
    },
    templateUrl: templateUrl,
    controller: controller,
    controllerAs: 'vm',
});

function controller($state, $scope) { ...
$scope.selectedElements = []; ...}

Upvotes: 1

Views: 540

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

You could simply consider passing a method to component, and call that method from component whenever you're changing selectedElements. Also for sec of make your application more performant follow one way data flow by making your bindings to use <(one way binding).

bindings: {
    data: "<",
    options: "<",
    selectedItemChange: '&'
},

and then your directive element will look like

<histogram-demo 
   options="options" 
   data="data" 
   selected-item-changed="itemChanged(items)">
</histogram-demo>

And whenever you changed vm.selectedItems variable inside controller component, do call vm.selectedItemChange({items: vm.selectedItems}), so the consumer of histogram-demo component will have method which will receive an selectedItems array.

Upvotes: 1

Related Questions