floatingpurr
floatingpurr

Reputation: 8559

AngularJS: triggering a controller function when a variable changes into a directive

I have a directive to do 2 things: (i) it manages the visualization of some tabs in HTML, (ii) it $watches the value of the object myObj in session storage and saves this object in a variable called myData. Here there is the code:

.directive('panelManager', function(){
    return {
        restrict: 'E',
        templateUrl: 'foo.html',

        controller: ['$scope', '$window',  function($scope, $window) {
            pn = this;
            pn.tab = 1; // init

            this.selectTab = function(setTab) {
                pn.tab = setTab;
            };

            this.isSelected = function(checkTab) {
                return pn.tab === checkTab;
            };

            $scope.$watch(function () {
                return $window.sessionStorage.getItem('myObj');
            }, function (value) {
                pn.myData = JSON.parse(value);
            });
        }],
        controllerAs: 'panels'
    };
})

I have a controller to call a WS passing a property foo of the aforementioned myData, every time it changes. Here it is:

.controller('MyDataController', ['$http', function($http) {

    pdc = this;
    pdc.myResultset = [];

    pdc.getDetails = function(val) {
        return $http.get("myUrl"+val+"/").then(function(response){
              pdc.myResultset= response.data;
        });
    };
}]);

Is there a way to trigger getDetails in that controller and to pass val = MyData.foo to it every time myData changes value? In this way, I could store in myResultset the current resultset of the WS and assign it to local scope.

Upvotes: 2

Views: 1774

Answers (1)

Erazihel
Erazihel

Reputation: 7605

You can emit from your directive, but you need the $rootScope in the associated controller. So the declaration becomes:

controller: ['$rootScope', '$scope', '$window',  function($rootScope, $scope, $window) {

Then, you could do something like this:

$scope.$watch(function () {
    return $window.sessionStorage.getItem('myObj');
}, function (value) {
    pn.myData = JSON.parse(value);
    $rootScope.$broadcast('valueChanged', pn.myData);
});

And in your controller:

.controller('MyDataController', ['$http', '$scope', function($http, $scope) {

    pdc = this;
    pdc.myResultset = [];

    pdc.getDetails = function(val) {
        return $http.get("myUrl"+val+"/").then(function(response){
            pdc.myResultset= response.data;
        });
    };

    $scope.$on('valueChanged', function(event, data) {
        pdc.getDetails(data.foo); //pass data.foo to the function
    });
}]);

Upvotes: 2

Related Questions