javascript - angularjs:使用 $compile 时指令中的范围问题

标签 javascript angularjs angularjs-directive

使用 $compile 为我的指令创建动态模板时,我遇到范围丢失的问题。请参阅下面的代码(为清楚起见进行了 trim ):

(function () {
'use strict';

angular.module('cdt.dm.directives').directive('serviceSources', ['$http', '$templateCache', '$compile', '$parse',
function ($http, $templateCache, $compile, $parse) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            type: '=',
            sources: '='
        },
        link: function (scope, element, attr) {
            var template = 'Template_' + scope.type + '.html';

            $http.get(template, { cache: $templateCache }).success(function (tplContent) {
                element.replaceWith($compile(tplContent)(scope));
            });

            $compile(element.contents())(scope);
        }
    }
}
])
})();

可以正常工作并且 html 模板已加载。

html 模板如下所示:

<table>
<thead>
    <tr>
        <th>File</th>           
    </tr>
</thead>
<tbody data-ng-reapeat="src in sources">
    <tr>
        <td>{{src.fileName}}</td>
    </tr>
</tbody>

sources 是一个包含两个元素的数组。在指令的范围内,它绝对是正确的,但在模板中,ng-repeat不起作用(我猜是因为现阶段源未定义)。

有人知道我做错了什么吗?

最佳答案

我认为有一个拼写错误:ng-repeat而不是data-ng-reapeat ,和ng-repeat应放在 <tr>

<table>
<thead>
    <tr>
        <th>File</th>           
    </tr>
</thead>
<tbody>
    <tr ng-repeat="src in sources">
        <td>{{src.fileName}}</td>
    </tr>
</tbody>

请注意$http.get是异步的,记得将代码包装在 scope.$apply 内。您应该像这样修改您的代码:

link: function (scope, element, attr) {
            var template = 'Template_' + scope.type + '.html';

            $http.get(template, { cache: $templateCache }).success(function (tplContent) {
              scope.$apply(function(){ 
                element.replaceWith(tplContent);
                $compile(element)(scope);
                //Or
                //element.html(tplContent);
                //$compile(element.contents())(scope);
               });
            });
        }

关于javascript - angularjs:使用 $compile 时指令中的范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19182823/

相关文章:

javascript - 无法弄清楚为什么 JS 会提示对象未定义

javascript - 在 Node 中获取请求后从 mongolab 获取空 JSON

javascript - 在同一 View 中使用相同的指令并绑定(bind)不同的数据

javascript - Angular leaflet指令点击事件在移动设备上不起作用

angularjs - 如何在 Angular js中制作自定义指令或在指令中传递变量

javascript - 为什么我们需要网络套接字?

javascript - Socket.io.js 未加载

javascript - 如何让选择选项与禁用和启用提交按钮一起使用

angularjs - 使用类或接口(interface)方法的类型

angularjs重新初始化tinyMCE textarea content_css选项