gpt4 book ai didi

javascript - 将 HTML 内容作为属性动态传递给 Angular 指令

转载 作者:行者123 更新时间:2023-12-03 05:27:27 24 4
gpt4 key购买 nike

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

我通过将 JSON 数据读入范围并将其传递给我编写的用于将 HTML 加载到模板中的指令来完成此操作。

Controller

.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>

我在这里缺少什么?

最佳答案

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

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

新指令:

.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}}'
};
})

关于javascript - 将 HTML 内容作为属性动态传递给 Angular 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41094310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com