我正在创建一个指令,您可以在其中传递不同类型的 html 元素并将它们注入(inject)到表格中。
但是有时我的用户可能需要在 ng-class 指令中添加某种表达式
例如检查以下内容:
$scope.element =
{
html: '<button type="button" ng-class="element.classExpression">My button</button>',
classExpression : "element.classExpressionDefault ? 'btn-success': 'btn-danger'",
classExpressionDefault: $scope.inactive,
}
HTML:
<span ng-bind-html-unsafe="element.html"> </span>
请注意上面的代码不起作用!
上面代码的问题是表达式没有被计算,因此它丢失了。
所以我的问题是我该如何添加它,这可能吗?
最佳答案
正如 Brant 在他的回答中已经暗示的那样,您可以从指令中编译 $scope.element
的 html 来计算 Angular 表达式。
为此,您需要注入(inject) $compile
服务并使用 element.html
上的指令 $scope
调用它:
angular.module('ui.directives', []).directive('exampleDirective', ['$compile',
function ($compile) {
return {
restrict: 'E',
scope: { element: '=' },
template: '<span ng-bind-html-unsafe="element.html"></span>',
link: function ($scope, element, attrs, controller) {
$scope.element = {
html: 'I am an <code>HTML</code>string with <p style="color: {{element.color}}">color</p>',
color: 'red'
}
$scope.element.html = $compile($scope.element.html)($scope);
}
};
}]);
当然,您可以通过使用该指令的模板传入元素并将其定义为父 Controller :
$scope.element = {
html: 'I am an <code>HTML</code>string with <p style="color: {{element.color}}">color</p>',
color: 'red'
}
模板:
<example-directive element="element"></example-directive>
JSFiddle:http://jsfiddle.net/8fw1gbrt/
关于javascript - 来自对象属性的html上的angularjs ng-class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38789044/