【问题标题】:Dynamically passing HTML content to Angular directives as attributes动态地将 HTML 内容作为属性传递给 Angular 指令
【发布时间】:2016-12-12 04:40:21
【问题描述】:

我正在尝试使用 Angular 动态加载存储在 JSON 文件中的一些 HTML。

我通过将 JSON 数据读入一个作用域并将其传递给我编写的用于将 HTML 加载到模板中的指令来做到这一点。

控制器

.controller('testCtrl', function($scope, $http, $state){

    $http.get('views/foo.json').then(function(res){

      $scope.somehtml = res.data;

    });

}) 

指令

.directive('loadHtml', function($compile){

        return {
        restrict: 'AE',
        scope: {
            content: "@",
        },
        link: function(scope, element, attrs) {
            scope.content = attrs.content;
            element.html(scope.content).show();
            $compile(element.contents())(scope);
        },
        template: '{{content}}'
    };

})

这行得通!

<load-html content="hello success"></load-html> 

这不是:(

<load-html content="{{somehtml}}"></load-html>

我在这里错过了什么??

【问题讨论】:

    标签: javascript jquery html angularjs json


    【解决方案1】:

    自己找到了解决方案,也许这对某人有帮助:

    我需要“观察”指令中的属性值。

    新指令:

    .directive('loadHtml', function($compile){
    
        return {
            restrict: 'AE',
            scope: {},
            link: function(scope, element, attrs) {
    
                attrs.$observe('content', function(val) { /* $observing the attribute scope */
                    scope.content = val;
                    element.html(scope.content).show();
                    $compile(element.contents())(scope);
                })
            },
            template: '{{content}}'
        };
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-27
      • 2016-05-10
      • 2021-12-23
      • 1970-01-01
      • 2014-10-18
      • 2015-11-29
      相关资源
      最近更新 更多