Marrying SignalR and Angular.js

Another quick post on how to use SignalR with Angular.

In short – just put SignalR js code inside the controller function, and it works, with a few catches.

 

Basic hub:

public class AdminHub : Hub
{
	public void Send(string text)
	{
	    this.Clients.receive("You have sent this -> " + text);
	}
}

HTML code:

 

<!DOCTYPE html>
<html>
<head>

    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.8.0.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.signalR-0.5.2.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/angular.js")" type="text/javascript"></script>
    <script src="/signalr/hubs" type="text/javascript"></script>
</head>
<body>
    <div id="content" ng-controller="SignalController">
        <input type="text" id="txt" placeholder="enter your text here" ng-model="txt" />
        <input type="button" id="btn" value="push" ng-click="send()" /><br />
        <br />
        Received: <span>{{txt2}}</span>
    </div>

    <script type="text/javascript">
        $(function () {
            angular.bootstrap(document, []);
        });


        function SignalController($scope) {
            var adminHub = $.connection.adminHub;
            $.connection.hub.start();

            $scope.send = function () {
                adminHub.send($scope.txt.toString());
            }

            adminHub.receive = function (data) {
                $scope.$apply($scope.txt2 = "'" + data + "'");
            }
        }
    </script>
</body>
</html>

 

 

Two things to watch for:

The angular’s model is being updated from outside of angular context, so we need to call $apply function.

Hub returns a string, and when assigning the property in $scope – make sure the value is wrapped in quotes.

Leave a Reply

Your email address will not be published. Required fields are marked *