Fabrizio Bartolomucci
Fabrizio Bartolomucci

Reputation: 4958

$window.addEventListener not triggered in angular

I am trying to refresh an angular table when a message arrives informing new data is ready; I am trying to use this code following the hint at: Listen to window events in an Angularjs service, but the event is not even received when command:

 parent.postMessage("printComments", "*");

is sent by another page in a frame.

What is the business?

<div ng-controller="MyCtrl" ng-app="myapp">
        <table ng-table="commentsTable">
            <tr ng-repeat="item in obj.data track by $index">
                <td class="plantCell">{{item.nome}}: </td>
            <td class="statusCell">{{item.status}}</td>
            <td class="statusCell">{{item.testo}}</td>
        </tr>
        </table>
        </div>
        <script language="javascript">
            var app=angular.module('myapp', []);
            var printOperation;
            function GetFromLocalStorage(key) {
                var items=localStorage.getItem(key);
                console.log(items);
                if (items===null){
                    console.log("item null");
                    return null;
                } else {
                if (typeof items!= "string") {items = JSON.stringify(items);}
                    return items;
                }
            }
            app.service('servicename', function($window, $rootScope) {
                function subsFunc() {
                        $window.addEventListener('printComments',
                            function(e) {
                                alert("arriva evento");
                                $rootScope.$broadcast('app.clickEvent', e);
                             });
                    }
                    return {
                            "subscribeMe": subsFunc
                    }
            });
            app.controller('MyCtrl',
                function($scope,servicename) {
                    $scope.data = {};
                        $scope.printComments = function() {
                //$scope.obj=GetFromLocalStorage("AllComments");
                            $scope.data.obj = [{
                            "nome": "first",
                            "status": 1,
                            "testo": "Rottura rullo 1!!!"
                            }, {
                            "nome": "second",
                            "status": 0,
                            "testo": "Rottura rullo fsdfsf!!!"
                            }];
                            console.log("ricevo evento e ricarico tabella");
                            console.log($scope.data.obj);

                        }
                        servicename.subscribeMe();
                        $scope.$on('app.clickEvent', function(a, b) {
                            console.log("evento");
                            alert("on received");
                            $scope.printComments();
                    });
                }
            )

Upvotes: 2

Views: 2817

Answers (2)

Gaurav Srivastava
Gaurav Srivastava

Reputation: 3232

You had some error in you code. I fixed it look at the snippet. there is no event printComments in $window object so i changed it to load for demo purpose, you could change it according to your need.

You forgot to inject the service in your controller, so your event listener was not registered.this line:

servicename.subscribeMe();

// Create IE + others compatible event handler
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child window
eventer(messageEvent,function(e) {
  console.log('parent received message!:  ',e.data);
  $(window).trigger(e.data);
},false);

  var app=angular.module('myapp', []);
  var printOperation;
  function GetFromLocalStorage(key) {
    var items=localStorage.getItem(key);
    console.log(items);
    if (items===null){
      console.log("item null");
      return null;
    } else {
      if (typeof items!= "string") {items = JSON.stringify(items);}
      return items;
    }
  }
  app.service('servicename', function($window, $rootScope) {
    function subsFunc() {
      //$($window).on("printComments", function(e){
      $($window).on("printComments",
        function(e) {
          alert("arriva evento");
          $rootScope.$broadcast('app.clickEvent', e);
        });
    }
    return {
      "subscribeMe": subsFunc
    };
  });
  app.controller('MyCtrl',
    function($scope,servicename,$timeout) {
      $scope.data = {};
      $scope.printComments = function() {
                //$scope.obj=GetFromLocalStorage("AllComments");
                $scope.data.obj = [{
                  "nome": "first",
                  "status": 1,
                  "testo": "Rottura rullo 1!!!"
                }, {
                  "nome": "second",
                  "status": 0,
                  "testo": "Rottura rullo fsdfsf!!!"
                }];
                console.log("ricevo evento e ricarico tabella");
                console.log($scope.data.obj);

              };
              servicename.subscribeMe();
              $scope.$on('app.clickEvent', function(a, b) {
                console.log("evento");
                alert("on received");
                $timeout(function(){
                   $scope.printComments();
                });
               
              });
            });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-controller="MyCtrl" ng-app="myapp">
  <table servicename>
    <tr ng-repeat="item in data.obj track by $index">
      <td class="plantCell">{{item.nome}}: </td>
      <td class="statusCell">{{item.status}}</td>
      <td class="statusCell">{{item.testo}}</td>
    </tr>
  </table>
<iframe src="//sample ifream with postmessage script"></iframe>
</div>

Upvotes: 2

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41447

where is your controller? you need to define the controller in the js

var app = angular.module('myapp', []); 
app.controller("MyCtrl", function($scope) {

$scope.obj = [{nome:"Sss"}]
})
var printOperation;

function GetFromLocalStorage(key) {
    var items = localStorage.getItem(key);
    console.log(items);
    if (items === null) {
        console.log("item null");
        return null;
    } else {
        if (typeof items != "string") {
            items = JSON.stringify(items);
        }
        return items;
    }
}
app.service('serviceName', function($window, $rootScope) {
    function subsFunc() {
        $rootScope.printComments = function() {
            //$rootScope.obj=GetFromLocalStorage("AllComments");
            $rootScope.obj = [{
                "nome": "first",
                "status": 1,
                "testo": "Rottura rullo 1!!!"
            }, {
                "nome": "second",
                "status": 0,
                "testo": "Rottura rullo fsdfsf!!!"
            }];
            console.log("ricevo evento e ricarico tabella");
            console.log($rootScope.obj);

        }

        $window.addEventListener('printComments',
            function(e) {
                console.log("ricevo evento");
                $rootScope.printComments();
            })
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="MyCtrl">
        <table ng-table="commentsTable">
            <tr ng-repeat="item in obj track by $index">
                <td class="plantCell">{{item.nome}}: </td>
            <td class="statusCell">{{item.status}}</td>
            <td class="statusCell">{{item.testo}}</td>
        </tr>
        </table>
        </div>

Upvotes: 1

Related Questions