问题
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