2014-10-11 88 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