【问题标题】:angularjs ng-class on html from object property来自对象属性的html上的angularjs ng-class
【发布时间】:2016-12-11 20:35:32
【问题描述】:

我正在创建一个指令,您可以在其中传递不同类型的 html 元素并将它们注入到表格中。

但有时我的用户可能需要在 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>

请注意上面的代码不起作用!

上面代码的问题是表达式没有被计算,因此它丢失了。

所以我的问题是我如何添加它,这可能吗?

【问题讨论】:

  • 我认为这是因为 Angular 只注入干净的 html 并照此处理。它不会将其作为角度编译的 html 处理,因此它不会评估其中的任何表达式。
  • 查看this answer如何实现这一点
  • @devqon 问题在于它是 uisng $watch 与 ng-repeat 一起使用时会出错

标签: javascript angularjs ng-class


【解决方案1】:

正如 Brant 在他的回答中已经暗示的那样,您可以在指令中编译 $scope.element 的 html 以评估角度表达式。

为此,您需要注入$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);
        }
    };
}]);

当然你可以通过使用该指令的模板传入元素,并让它定义父控制器:

$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/

【讨论】:

  • 我可以看到它适用于您的小提琴但是我无法使其在我的项目中工作我得到以下信息:错误:语法错误,无法识别的表达式:我是 HTML带有

    color

    的字符串
【解决方案2】:

要做你想做的事,你可能需要注入 $compile 并即时编译元素。另一种选择是传递稍微不同的选项,并稍微不同地配置你的 DOM 以做出反应。

JSON:

$scope.inputs = [{
    type: 'text',
    classComparisonValue: 'someClass', // omit perhaps for other logic on DOM?
    model: 'myKey'
}]

还有你的 DOM:

<div ng-repeat="input in inputs">
    <input type="text" class="input.class" 
          ng-model="inputAnswer[input.model]" 
          ng-if="input.type == 'text" 
          ng-class="{ 'btn-danger': input.classComparisonValue, 
                      'btn-success': !input.classComparisonValue">
    // Add other input types here with ng-if
</div>

【讨论】:

  • 遗憾的是我不能做到以上我需要整个 html 成为一个 javascript 字符串
  • $compile 那么你可能会去。
  • 你能举个例子吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-05
  • 2017-04-13
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多