user3293156 user3293156 - 1 month ago 13
Javascript Question

Control angularjs ui switch from external event

I have a angularjs material ui switch. I want to change its status when an external event happens. This external event is a mqtt message received on one of the published topic. I am using node.js mqtt client running on a browser.

<div ng-controller="SWCtrl">
<md-switch ng-model="switch_status.sw1" aria-label="Switch"
ng-change="onChange(switch_status.sw1)">
Switch: {{ switch_status.sw1 }}
</md-switch>
</div>


The corresponding controller code;

angular.module('myApp.controllers', [])
.controller('SWCtrl', ['$scope',
function ($scope, ) {
$scope.switch_status = {
sw1: true,
};

var mqtt_client = mqtt.connect('ws://127.0.0.1:3000');
mqtt_client.subscribe('hello/world');
mqtt_client.on('connect', function () {
console.log("MQTT connected");
});

mqtt_client.on("message", function(topic, payload) {
console.log([topic, payload].join(": "));
if (topic === "hello/world" && payload.toString() === "switch on")
{
console.log("message on");
$scope.switch_status.sw1 = true;
}
else if (topic === "hello/world" && payload.toString() === "switch off")
{
console.log("message off");
$scope.switch_status.sw1 = false;
}
});

$scope.onChange = function (sw_state) {
if (sw_state === true) {
mqtt_client.publish('hello/world', 'switch on');
}
else if (sw_state === false) {
mqtt_client.publish('hello/world', 'switch off');
}
}
}])
;


The code segment in the controller that gave me problem is here;

mqtt_client.on("message", function(topic, payload) {
console.log([topic, payload].join(": "));
if (topic === "hello/world" && payload.toString() === "switch on")
{
console.log("message on");
$scope.switch_status.sw1 = true;
}
else if (topic === "hello/world" && payload.toString() === "switch off")
{
console.log("message off");
$scope.switch_status.sw1 = false;
}
});


When an external event happens, I want to change the switch status. How I did it was running the line of code below;

$scope.switch_status.sw1 = true;


Unfortunately, this does not work. How to make the switch change status when the external event happens?

Answer

try $scope.$apply() after the

$scope.switch_status.sw1 = true;

basically it wasn't an angular event so angular has no idea that the variable was even change. scope.apply will force another digest cycle

Comments