简体   繁体   中英

Angular / Socket.io / HTML / Calling a Controller's Function from WITHIN <script> in HTML

I am trying to call a controller's function from within a script tag in my index.html.

<script>
    var socket = io.connect('192.168.1.103:3000');
    socket.emit('pusharduino', "SOCKET DATA FROM ANGULAR");
    socket.on('pushangular', function (data) {
        testFunction();
    });
</script>

<button ng-controller="BaseCtrl" ng-click="testFunction()"></button>

The socket.io connection works fine. It connects to my server and whenever I emit anything either way it sees it just fine. The issue is "testFunction()" is not defined apparently.

The button directly below it works fine! The "testFunction()" function is defined in the BaseCtrl controller of my app. Obviously since I attached that controller to the button I am able to call the function.

The question is; how do I call that same function from within my socket.io script there? Or any script tag for that matter? Doesn't even need to be socket.io, its just that socket.io is the trigger for this specific event.

I assume it is some scope issue here and that script clearly doesn't have access to the BaseCtrl. I am able to print out global variables that are in my app.js though.

THINGS I'VE TRIED: - Attaching the BaseCtrl to the script tag. - Using $scope all over the place. - Referencing the testFunction() in every way I can think of.

CODE FOR BaseCtrl

angular.module('yapp')
 .controller('BaseCtrl', function($scope) {

   $scope.testFunction = function() {
     console.log("testFunction() has been called!);
   }

});

----------------------------------------------------------------------------

(tl;dr)

IN SUMMARY: How can I make a function in my app available to my html so that whenever socket.on('whatever') is triggered, that function will be called? I don't care if the function is in a factory, a service, a controller, doesn't matter to me. I just need to update a bunch of variables in my app whenever they are received from the server via socket.io

In your script you can do the following

var parentScope = window.parent.angular.element(document.body).scope();
parentScope.$emit("MyEvent", { payload: "MyPayload"});

In your controller you can just listen to the event.

$scope.$on("MyEvent", function (evt, args) {
//arg is your payload
}

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM