gpt4 book ai didi

javascript - 从外部事件控制angularjs ui切换

转载 作者:行者123 更新时间:2023-11-30 12:09:57 24 4
gpt4 key购买 nike

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

对应的 Controller 代码;

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

Controller 中给我带来问题的代码段在这里;

        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 将强制另一个摘要循环

关于javascript - 从外部事件控制angularjs ui切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34100807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com