0

Recently I have begun to integrate AngularJS in project. Before I have written many prototypes and single functions in JavaScript, for example (Node.js + socket.io functionality).

Today I a have trouble communicating AngularJS with clear JavaScript:

JS:

socket.on('message', function (data) {
     showSystemMessage();
}

function showSystemMessage(message) {
     // Increment here AngularJS $scope.messagesCnt++ ?;
}

AngularJS:

.controller('MessagesController', ['$scope', function($scope) {
    $scope.messagesCnt = 0;
}])

HTML:

<div>{{messagesCnt}}</div>

Please, attention to method: showSystemMessage()

1
  • are you getting any errors? is the showSystemMessage() defined in the angular file? else it won't have access to $scope Commented Mar 30, 2015 at 6:40

3 Answers 3

2

Ideally, You should follow what @Yaseer has said, but i see, that you're using Socket IO native implementation [No angular Wrapper around].

Hence, you have two solutions :

  1. Use Angular Socket IO

  2. Access Angular Controller from the native javascript :

For this you must have an element with an identifier ID. then you can use the id to access the associated scope.

angular.element("#your-identifier-id-here").scope().messagesCnt++;
Sign up to request clarification or add additional context in comments.

Comments

0

Write your socket listener code inside controller

function appcontroller($scope){

   socket.on('message', function (data) {
    showSystemMessage();
   }

   function showSystemMessage(message) {
      $scope.$apply(function(){
      // Increment here AngularJS $scope.messagesCnt++ ?;
    });
   }
}

Comments

0

If you function showSystemMessage is outside the controller scope, there is no way you can update the scope variable messagesCnt. (There are but not straight forward.)

Instead this function of yours should reside in an angular service instead, and then on whatever event you want you could broadcast a message from your service to your controller to update its count value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.