user1985943
user1985943

Reputation: 83

Not Getting updated data in custom directive

I have a method available in another controller and it is returning current report data and when ever i change the report i am not getting new data in my directive and it is still showing old data and if i refresh the browser it is giving new data.

angular.controller("sample", ['$http', '$scope', function($http, $scope){
     $scope.getNewsData = function(){
        var data = {name: XYZ}
        return data;
     }
}])

I am accessing above controller method inside my directive using isolate scope(&) and my question is how to get new data with out refreshing the browser.

angular.directive('myDir',function(){
     return {
      restrict:'A',
      scope:{
           getNewsData :&getnew;
       },
      controller:'myDirController',
      templateUrl: 'news.html',
      link:function(scope, $elm, attr){           
          var obj = scope.getNewsData 
      } 
   }
});

Please help me and thanks in advance.

Upvotes: 0

Views: 76

Answers (1)

Vicruz
Vicruz

Reputation: 331

Have you tried using $rootScope.$broadcast and $scope.$on?

in directive you will add a listener everytime you change the data.

app.directive('myDir',function(){
  return {
      scope:{
           getNewsData :"&"
       },
      link:function(scope, $elm, attr){           
        var obj = scope.getNewsData(); 
        var cleanup = scope.$on('changeValue', function() {
          console.log(scope.getNewsData());
          obj = scope.getNewsData();
        })

       //make sure to destroy to avoid memory leaks
        scope.$on('$destroy', cleanup);
      } 
   }
});

to the method that change the value you must add $rootScope.$broadcast

app.controller('OtherCtrl', function($scope,$rootScope,MainService) {
  $scope.changeValue = function() {
    MainService.setter("xyz");
    $rootScope.$broadcast('changeValue');
  }
});

I just add factory for simple passing of data(setter/getter)

app.factory('MainService', function() {
  var data;
  return {
    getter: function() {
      return data;
    },
    setter: function(value) {
      data = value;
    }
  }

})
For working demo click here

Upvotes: 1

Related Questions