2014-10-11 85 views
0

所以我們有這個非常好的項目。藍牙LE,通過調用本地代碼通知javascript,然後角度...AngularJS沒有更新的視圖

現在我們陷入了這個爛攤子。

數據綁定起初看起來非常漂亮,但使用之後,它變得越來越糟。

所以這裏是代碼:

controllers.controller('DashboardCtrl', function($scope) { 
    $scope.as = Demo.results[GATT.Dashboard.as]; 
    $scope.ac = Demo.results[GATT.Dashboard.ac]; 
    $scope.av = Demo.results[GATT.Dashboard.av]; 
    $scope.ps = Demo.results[GATT.Dashboard.ps]; 
    $scope.cs = Demo.results[GATT.Dashboard.cs]; 
    $scope.ts = Demo.results[GATT.Dashboard.ts]; 
    $scope.dd = Demo.results[GATT.Dashboard.dd]; 
    $scope.rc = Demo.results[GATT.Dashboard.rc]; 
    $scope.tps = Demo.results[GATT.Dashboard.tps]; 
    $scope.ls = Demo.results[GATT.Dashboard.ls]; 
    $scope.bm = Demo.results[GATT.Dashboard.bm];  
}); 

的Demo.results對象持有我們的藍牙設備推入值。

我們現在必須「簡單地」在視圖中顯示它。

上面的例子是剩下的代碼,因爲$ apply會給$消化循環帶來錯誤。

$ watch正在工作,但似乎無法在視圖中顯示更改的值。

因此,我可以提醒自己一個變量已經改變,但是我們無法獲得在視圖中實際顯示的值。

有沒有人比我們更瞭解這個系統?因爲這應該是關於angularjs最有價值的東西之一。它剛剛壞了。或者我們破壞了它。

回答

0

嘗試調用$scope.safeApply()方法。並用此方法包裝視圖更新代碼。這將確保得到很好的更新:

controllers.controller('DashboardCtrl', function($scope) { 
    $scope.safeApply($scope.viewUpdate()); // Call this code from the intended function, like an API call back or something where you wish to get your view uodated. 

    $scope.safeApply = function(fn) { 
     var phase = this.$root.$$phase; 
     if(phase == '$apply' || phase == '$digest') { 
     if(fn && (typeof(fn) === 'function')) { 
     fn(); 
     } 
     } else { 
     this.$apply(fn); 
     } 
    }; 

    $scope.viewUpdate = function() { 

    $scope.as = Demo.results[GATT.Dashboard.as]; 
    $scope.ac = Demo.results[GATT.Dashboard.ac]; 
    $scope.av = Demo.results[GATT.Dashboard.av]; 
    $scope.ps = Demo.results[GATT.Dashboard.ps]; 
    $scope.cs = Demo.results[GATT.Dashboard.cs]; 
    $scope.ts = Demo.results[GATT.Dashboard.ts]; 
    $scope.dd = Demo.results[GATT.Dashboard.dd]; 
    $scope.rc = Demo.results[GATT.Dashboard.rc]; 
    $scope.tps = Demo.results[GATT.Dashboard.tps]; 
    $scope.ls = Demo.results[GATT.Dashboard.ls]; 
    $scope.bm = Demo.results[GATT.Dashboard.bm]; 

    } 
}); 

參考: https://coderwall.com/p/ngisma/safe-apply-in-angular-js