您可以使用ng-bind-html
.
<li ng-repeat = "field in fields">
<div bind-html-compile ng-bind-html="trust(field)" > </div>
</li>
添加bind-html-compile
指令以编译 DOM,以便更改将影响 DOM 元素
指示
.directive('bindHtmlCompile', ['$compile', function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch(function() {
return scope.$eval(attrs.bindHtmlCompile);
}, function(value) {
element.html(value);
$compile(element.contents())(scope);
});
}
};
}]);
在trust
函数中将对象作为参数传递并返回 html 信任元素
$scope.trust = function(html) {
return $sce.trustAsHtml('<div ng-click = "' + html.action + '" > {{field.name}} </div>');
}
演示
angular.module("app",[])
.controller("ctrl",function($scope,$sce){
$scope.viewDetails = function(){console.log("viewDetails")}
$scope.sellProduct = function(){console.log("sellProduct")}
$scope.fields = {
"foo1":{
"name":"productDetails",
"displayAs":"button",
"action":"viewDetails()"
},
"foo2":{
"name":"sell",
"displayAs":"button",
"action":"sellProduct()"
}
}
$scope.trust = function(html){
return $sce.trustAsHtml('<div ng-click = "'+html.action+'" > {{field.name}} </div>');
}
}).directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
element.html(value);
$compile(element.contents())(scope);
});
}
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<li ng-repeat = "field in fields">
<div bind-html-compile ng-bind-html="trust(field)" > </div>
</li>
</div>