控制angularjs ui从外部事件切换

我有一个angularjs材料ui开关。 当外部事件发生时,我想改变它的状态。 这个外部事件是在已发布的主题之一上收到的mqtt消息。 我正在使用在浏览器上运行的node.js mqtt客户端。

<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> 

相应的控制器代码;

 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'); } } }]) ; 

给我问题的控制器中的代码段在这里;

  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.switch_status.sw1 = true; 

不幸的是,这是行不通的。 外部事件发生时如何使开关状态改变?

试试$ scope。$ apply()之后

 $scope.switch_status.sw1 = true; 

基本上这不是一个angular度事件,所以angular度不知道variables甚至是变化。 scope.apply将强制另一个摘要循环