Question

I am having a controller and a partial file. The partial file tries to access a variable which was set by the controller. But the issue here is that the controller populates the scope object with the variables by making a http call and because of this ajax request, by the time the http call returns the data, the partial file is already loaded and hence I get the variable as undefined. Also although the partial file is loaded on the browser, the data s getting populated after a delay since the scope values are getting binded after the http response returns.

Is there a way in AngularJs, to load the partial file/directives only after the http call in the controller gets the data so that the view is loaded with data instantaneously and not after some delay. Please let me know how to approach this problem.

Was it helpful?

Solution

If you are talking about the partials that get loaded in ng-view, you can use the $routeProvider resolve property on the route. This property can take a function which returns a value or promise. In case of promise the view only gets loaded once the promise is resolved. Your code would look something like

 $routeProvider.when('/', {
            templateUrl: 'app.html', 
            controller:myAppController, 
            resolve:{
                data:function($http){
                    return $http.get('url');   //this by default returns promise.
                }
            }
        });

In the controller now you can also inject the data property of resolve as parameter and access the data.

See this video too to understand resolve http://www.thinkster.io/angularjs/6cmY50Dsyf/angularjs-resolve-conventions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top