控制angularjs ui从外部事件切换

时间:2015-12-05 03:08:47

标签: javascript angularjs node.js mqtt

我有一个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;

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

1 个答案:

答案 0 :(得分:3)

之后尝试$ scope。$ apply()
$scope.switch_status.sw1 = true;

基本上它不是角度事件,所以角度不知道变量是否均匀变化。 scope.apply将强制执行另一个摘要周期