AngularJS:ng-include在动态html中不起作用

时间:2013-07-19 19:37:04

标签: angularjs

我是AngularJS的新手。我试图动态使用ng-include指令,但它不起作用。例如

var template = '<div ng-include="/app/partials/HtmlPage.html"></div>'

2 个答案:

答案 0 :(得分:15)

来自Angular docs

If the source is a string constant, make sure you wrap it in quotes, e.g. src="'myPartialTemplate.html'".

尝试将这些内部引号添加到字符串模板名称中。

var template = '<div ng-include="\'/app/partials/HtmlPage.html\'"></div>'

(注意你必须逃避你的内部引号,因为你已经在一个字符串中)

答案 1 :(得分:0)

您应该展示更多代码。我有一个指令,我正在使用我的指令模板中的ng-include动态加载和使用不同的模板。看到这是如何工作的,我无法想象你会做什么会导致ng-include无法工作。您是否检查过检查员或其他任何可以看到它加载HTMLPage.html或获得404?

directive("dynamicFormInput", ['$http', '$templateCache', function($http, $templateCache){
    return {
        restrict: 'E',
        scope: {model: '=', section: '='},
        template: '<ng:include src="tpl"></ng:include>',
        link: function(scope, iElement, iAttrs) {
            switch(scope.section.sectionTypeId)
            {
                case 1:
                    $http.get('partials/survey/textInput.html', {cache:$templateCache});
                    scope.tpl="partials/survey/textInput.html";
                break;
                case 2:
                    $http.get('partials/survey/selectOneOption.html', {cache:$templateCache});
                    scope.tpl="partials/survey/selectOneOption.html";
                break;
                case 3:
                    $http.get('partials/survey/multiSelectOption.html', {cache:$templateCache});
                    scope.tpl="partials/survey/multiSelectOption.html";
                break;
                case 4:
                    $http.get('partials/survey/boolean.html', {cache:$templateCache});
                    scope.tpl="partials/survey/boolean.html";
                break;
                case 5:
                    $http.get('partials/survey/multiSelectOption.html', {cache:$templateCache});
                    scope.tpl="partials/survey/multiSelectOption.html";
                break;
                case 6:
                    if(scope.section.sectionId == 19){
                        $http.get('partials/survey/addressSelection.html', {cache:$templateCache});
                        scope.tpl="partials/survey/addressSelection.html";
                    }
                break;
            }
        }
    }
}])