使用递归调用将 ajax 数据绑定到 ng-include 以加载模板 [英] Binding ajax data to ng-include with recursive call to load template

查看:25
本文介绍了使用递归调用将 ajax 数据绑定到 ng-include 以加载模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果标题很神秘,我正在尝试复制这个例子:http:///plnkr.co/edit/NBDgqKOy2qVMQeykQqTY?p=preview 并且它工作正常,但如果我通过 ajax 加载数据它不起作用.原来的控制器是:

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: '#',
        }
    ];
});

而我的是:

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

问题是 html 模板在之前加载数据,当数据准备好时,绑定已经应用.

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

工作示例(无 ajax):http://plnkr.co/edit/NBDgqKOy2qVMQeykQqTY?p=preview

不工作的例子(ajax):http://plnkr.co/edit/lF5VkRT67IybRQm5yTuB?p=preview

最好的方法是什么?

推荐答案

我不太确定我的修复,但是当我删除 ng-init="submenu = links;" 并替换为ng-model,那么它就可以工作了.

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

请看演示.也许是因为 ng-include 创建了自己的作用域,而 ng-init 以某种方式无法从作用域中获取值.

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.

这是我的修复:

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

$scope.submenu = $scope.links;

plunker 演示

这篇关于使用递归调用将 ajax 数据绑定到 ng-include 以加载模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆