2016-04-15 35 views
-2

如何從AngularJS廣播事件並在基本JS腳本中偵聽此事件。謝謝從AngularJS到Javascript的事件

+0

我們需要一些代碼。 – ayushgp

+0

你想做什麼?避免使用Jquery和Angular專門編輯DOM – AlainIb

+0

我使用angularJS連接到套接字,並且我有一些基本的JS應用程序。所以當套接字到來時,我需要從我的js代碼中調用函數。 – Gor

回答

1
<body data-ng-app="AngularApp"> 

    <script> 
    //my custom native JS Script 


    //normal Javscript function , can be called within AngularJS normally 
    function someJsFunction(){ 
     console.log('this is some JS function'); 
    } 



    // some Event handling and listentning to be fired wihtin AngularJS 
    function Event(sender) { 
     this._sender = sender; 
     this._listeners = []; 
    } 

    Event.prototype = { 
     attach: function (listener) { 
      this._listeners.push(listener); 
     }, 
     notify: function (args) { 
      var index; 

      for (index = 0; index < this._listeners.length; index += 1) { 
       this._listeners[index](this._sender, args); 
      } 
     } 
    }; 



    //Event Handling Usage 
    var myCutstomEvent = new Event(this); 

    myCutstomEvent.attach(function() { 
     console.log('myCustomEvent Handler'); 
    }); 



    </script> 
    <div ng-controller="myCtrl"> 
    <input type="button" ng-click="clickBtn()" value="clickme"/> 
    </div> 

</body> 

..... 和角碼

var app = angular.module("AngularApp", []); 

app.controller(
    'myCtrl', ['$scope', 'myService', 
    function($scope, myService) { 

    $scope.clickBtn = function(){ 
      console.log('buttonClicked in Controller'); 
      //call service 
      myService.someService(); 

      //fire normal Angular Event 
      $scope.$broadcast('myCustomAngularEvent'); 
     }; 


     //handle Angular Event and refire the JS Event 
     $scope.$on('myCustomAngularEvent', function() { 
      //Fire the JS Event 
      myCutstomEvent.notify(); 
     }) 

}]); 


app.service('myService', function() { 

    var someService = function() { 
     console.log('this is someService'); 
     someJsFunction(); 
    }; 

    var services = { 
     'someService' : someService 
    }; 

    return services; 
}); 

... ,控制檯也將顯示此:

buttonClicked in Controller 
this is someService 
this is some JS function 
myCustomEvent Handler 

歡呼