Binding ajax data to ng-include with recursive call to load template

五迷三道 提交于 2019-12-08 13:50:26

问题


Sorry if the title is quite cryptic, I'm trying to replicate this example: http://plnkr.co/edit/NBDgqKOy2qVMQeykQqTY?p=preview and it works fine, but if I load data via ajax it doesn't work. The original controller is:

app.controller('MainCtrl', function($scope) {
    $scope.links = [
        {
            text: 'Menu Item 1',
            url: '#',
        },{
            text: 'Menu Item 2',
            url: '#',
            submenu: [
                {
                    text: 'Sub-menu Item 3',
                    url: '#',
                },{
                    text: 'Sub-menu Item 4',
                    url: '#',
                    submenu: [
                        {
                            text: 'Sub-sub-menu Item 5',
                            url: '#',
                        },{
                            text: 'Sub-sub-menu Item 6',
                            url: '#',
                        }
                    ]
                }
            ]
        },{
            text: 'Menu Item 3',
            url: '#',
        }
    ];
});

while mine is:

app.controller('SiteTreeCtrl', function ($scope, $http) {
    $http.post('/ajaxsite/tree', { section: "website" }).success(function (data) {
        $scope.folders = data.links;
    });    
});

the problem is that the html template is loaded before the data and when data is ready the binding is already applied.

Working example (no ajax): http://plnkr.co/edit/NBDgqKOy2qVMQeykQqTY?p=preview

Not working example (ajax): http://plnkr.co/edit/lF5VkRT67IybRQm5yTuB?p=preview

What is the best way to to that?


回答1:


I am not exactly sure about my fix, but when I remove ng-init="submenu = links;" and replace with ng-model, then it works.

Please take a look at the demo. Maybe because ng-include creates its own scope and somehow the ng-init can not grab the value from the scope.

Here is my fix:

<div ng-include="'partialMenu.html'" ng-model="submenu"></div>

$scope.submenu = $scope.links;

Demo on plunker



来源:https://stackoverflow.com/questions/17946606/binding-ajax-data-to-ng-include-with-recursive-call-to-load-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!