2015-12-05 105 views
1

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; 

不幸的是,這是行不通的。外部事件發生時如何使開關狀態改變?

回答

3

試$範圍。$適用()後

$scope.switch_status.sw1 = true; 

基本上它不是一個角事件,這樣的角度不知道該變量是甚至改變。 scope.apply將強制另一個摘要循環