简体   繁体   中英

async data fetching and angular library

"I have the following problem: I would like to fetch json from async rest call and use it in some existing directives from an Angular library (in my case angular-ui-tree and angular-charts).

This is a simple example with angular-ui-tree for try to explain my problem . The service:

var mod = angular.module("user.services");
mod.factory("userService", ["$http",  function ($http) {

    return {
        getUserMenu: function () {
        //call rest
            return $http.get('/user/menu').then(function (response) {
                    return response.data;
            });
        }
    };
}]);

The controller:

var mod = angular.module("admin.controllers");
$scope.menu = [];
userService.getUserMenu().then(function(menuResp){
     $scope.menu = menuResp;
};
$scope.showbody = true;
$scope.selectedItem = {}; 
$scope.options = {};
...

Page (it's only a fragment):

<div ng-controller="MenuListCtrl">
<script type="text/ng-template" id="items_renderer.html">
   <div ui-tree-handle>... </div>
   <ol ui-tree-nodes="options" ng-model="item.items">
    <li ng-repeat="item in item.submenu" ui-tree-node ng-include="'items_renderer.html'"></li>
    </ol>
</script>
<div ui-tree="options">
<ol ui-tree-nodes ng-model="list" >
 <li ng-repeat="item in menu" ui-tree-node ng-include="'items_renderer.html'"></li>
</ol>
</div>

When I open my page the tree is correctly render but i have an error in console. In Angular-ui case the error is "Cannot read property '0' of undefined". I think it's because when controller was been loading menu var wasn't set.

Probably this way is wrong. I think the solution is render the angular-ui-tree fragment after data loading. Something like this:

var mod = angular.module("tnp.admin.controllers");
userService.getUserMenu().then(function(menuResp){
//render tree template with menuResp data or append in my fragment the angular-ui-tree directive with menuResp data
};

I have this problem with others libraries. The error is different but i think the base problem is the same. Someone can help my? How can I render my fragment this menu data? Thanks!!!

I don't see why menu would need to be declared in your service. You should make sure that $scope.menu is set to an empty array in your controller before you call the service to populate it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM