Sadeep Sadeep - 4 days ago 5
AngularJS Question

Asynchronous loading of views/handling promises in AngularJS views with jq-plot

I have a controller for a jq-plot as below:

app.controller('chartCtrl', ['$scope', 'Model1', 'Model2', function($scope, Model1, Model2) {
var model1 = new Model1();
model1.firstAsyncMethod(function() {
var model2 = new Model2();
model2.secondAsyncMethod(function() {
$scope.data = [ [1,6.5],[2,6.5],[3,7],[4,8],[5,7.5],[6,7],[7,6.8],[8,7],[9,7.2],[10,7],[11,6.8],[12,7] ];
})
});
}]);


As you can see , I'm first calling the
firstAsyncMethod()
and passes a callback to it. This call back makes another async call to
secondAsyncMethod()
. It's only at the end when this
secondAsyncMethod()
resolves my
$scope.data
becomes available.

In the meantime, my view for this controller looks like:

<div ng-controller="chartCtrl">
<div ui-jq="plot" ui-options="
[
{ data: {{data}}}
]
">
</div>
</div>


Now, the problem is when
ui-options
tries to load
data
on page load, the controller has not returned
data
yet. This throws parse errors in angularJS.

I tried to define the chart options in the controller after the second async method fully resolved but I still keep getting errors. How can I resolve this? Thanks.

Answer

Okay so I finally managed to find a simpler solution. All you need to do is add ui-refresh directive to the view:

<div ng-controller="chartCtrl">
<div ui-jq="plot" ui-refresh="data" ui-options="
      [
        { data: {{data}}}
      ]
    ">
</div>

In the controller you have to define data to some default value outside of the async calls to stop throwing the error:

app.controller('chartCtrl', ['$scope', 'Model1', 'Model2', function($scope, Model1, Model2) {
    $scope.data = [[0,0]];
       var model1 = new Model1();
       model1.firstAsyncMethod(function() {
          var model2 = new Model2();
          model2.secondAsyncMethod(function() {
            $scope.data = [ [1,6.5],[2,6.5],[3,7],[4,8],[5,7.5],[6,7],[7,6.8],[8,7],[9,7.2],[10,7],[11,6.8],[12,7] ];
          })
       });
    }]);
Comments