控制angularjsui从外部事件切换

Control angularjs ui switch from external event

我有一个 angularjs material 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 甚至不知道变量发生了变化。 scope.apply 将强制另一个摘要循环