2016-04-15 13 views
-2

AngularJSからイベントをブロードキャストし、このイベントを基本的なJSスクリプトで聞くにはどうすればよいですか。 ...AngularJSからJavascriptへのイベント

+0

を我々は必要いくつかのコード。 – ayushgp

+0

あなたは何をしたいですか? DOMを編集するためにAngularを使ってJqueryを使わないでください – 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 

歓声

関連する問題