gpt4 book ai didi

javascript - 如何在净化后的 HTML 字符串中消化我的 Angular 指令? | AngularJS

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

在通过 ng-bind-html-unsafe 将 $scope.content 对象插入 DOM 后,我无法重新编译在 $scope.content 对象中找到的 Angular 代码。有人知道如何让 Angular 消化这段代码吗?提前非常感谢!

PLUNKER HERE

###index.html###
<body ng-controller="MainCtrl">
<h2>HTML Testing</h2>
<div ng-bind-html-unsafe="content.iPhone"></div>
</body>

###app.js###
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
$scope.content = {
iPhone: "<div ng-style=\"style.iPhoneTest\">This shows up on an iPhone</div>",
iPad: "<div ng-style=\"style.iPadTest\">This shows up on an iPad</div>",
androidPhone: "<div ng-style=\"style.androidPhoneTest\">This shows up on an Android phone</div>",
androidTablet: "<div ng-style=\"style.androidPhoneTablet\">This shows up on an Android tablet</div>"
};
$scope.style = {
iPhoneTest: {background: 'blue', color: 'black'},
iPadTest: {background: 'black', color: 'white'},
androidPhoneTest: {background: 'yellow', color: 'black'},
androidTabletTest: {background: '#111', color: 'white'}
};
});

最佳答案

为什么不使用指令而不是注入(inject)?

<body ng-controller="MainCtrl">
<h2>HTML Testing</h2>
<div ng-my-phones="style"></div>
</body>

app.directive("ngMyPhones", function(){
return {
scope: {
"style": "=ngMyPhones"
},
template: '<div ng-style=\"style.iPhoneTest\">This shows up on an iPhone</div>'+
'<div ng-style=\"style.iPadTest\">This shows up on an iPad</div>'+
'<div ng-style=\"style.androidPhoneTest\">This shows up on an Android phone</div>'+
'<div ng-style=\"style.androidPhoneTablet\">This shows up on an Android tablet</div>'
}
});

否则你必须使用$compile来告诉Angular将范围应用到自定义html上,但这是一个丑陋的方法。

如果您想动态决定显示哪部手机,您可以将 $scope.contents 数组传递到指令 $compile 中,并像这样手动附加元素:

<body ng-controller="MainCtrl">
<h2>HTML Testing</h2>
<div ng-my-phone="content.iPhone" ng-my-phone-style="style"></div>
</body>
</html>


app.directive("ngMyPhone", function($compile){
return {
scope: {
"ngMyPhone": "=",
"style": "=ngMyPhoneStyle"
},
link: function($scope, $element){
var oldPhoneElement;

//Everytime the phone
$scope.$watch("ngMyPhone", function(newContent){
angular.element(oldPhoneElement).remove();
oldPhoneElement = angular.element(newContent);

$compile(oldPhoneElement)($scope);
$element.append(oldPhoneElement);
});
}
};
});

WORKING PLUNKER

关于javascript - 如何在净化后的 HTML 字符串中消化我的 Angular 指令? | AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24399117/

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