2013-11-25 54 views
2

在deviceready事件觸發後,有什麼方法可以在我的angular應用中設置$ rootScope變量?

var application = { 
// Application Constructor 
initialize: function() { 
    this.bindEvents(); 
}, 

// Bind any events that are required on startup. Common events are: 
// 'load', 'deviceready', 'offline', and 'online'. 
bindEvents: function() { 
    document.addEventListener('deviceready', this.onDeviceReady, true); 
}, 
// deviceready Event Handler 
onDeviceReady: function() { 
    //set angular app $rootScope variable 
} 

};

回答

3

要在deviceready事件處理程序設定在$ rootScope的屬性,確保將其包裝在$ apply方法調用,因爲deviceready事件發生AngularJS之外。下面是一個例子:

angular.module('myapp').run(['$rootScope', function($rootScope) { 
    document.addEventListener('deviceready', function() { 
     $rootScope.$apply(function() { 
      $rootScope.myVariable = "variable value"; 
     }); 
    }); 
}); 
+0

這個應該可以的,試試看吧。謝謝。 –

+0

你在哪裏寫這個? 我在index.js文件中有我的onDeviceReady事件,並且我在main.js中創建了我的angular應用程序模塊。那我應該複製一下嗎? – Laureant

相關問題