javascript - Angular强制页面执行指令添加了html属性

标签 javascript html angularjs

我有一个指令,可以将 spellcheck 属性添加到 2 个 div 中,如下所示:

(function(){  

  'use strict';

  app.directive('spellchecker', spellchecker);
  spellchecker.$inject = ['$timeout', '$compile'];

  function spellchecker($timeout, $compile) {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
          attrs.$set('contenteditable', true);
          attrs.$set('spellcheck', true);
          $compile(element)(scope); //<- this does not seem to do the trick for me.
        }
      }
    };
  };
})();

哈姆尔

.title(spellchecker="{{!!preview}}") {{thing.title}}

spellchecker="{{!!preview}}") 解析为 true。

我也尝试通过用 div 包装 html 来实现相同的目标,无需使用指令,如下所示:

%div{'spellcheck':'true', 'contenteditable':'true'}
  .title {{thing.title}}

我希望指令在页面 div 上强制进行拼写检查,但目前拼写检查仅在单击添加了拼写检查属性的两个 div 中的任何一个时才起作用。 我必须编译 div 的 html 吗?

最佳答案

简而言之,答案是肯定的,您需要编译添加的属性,否则它们将仍然是纯 HTML,没有任何用处。

您只需将 $compile 添加到依赖项并使用它即可做到这一点:

link: function(scope, element, attrs) {
      attrs.$set('contenteditable', true);
      attrs.$set('spellcheck', true);
      $compile(element)(scope);  //element will contain added directives
  }

关于javascript - Angular强制页面执行指令添加了html属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39334760/

相关文章:

javascript - jQuery .focus() 回调不起作用

javascript - requestAnimationFrame 没有取消

javascript - 未捕获的类型错误 : Cannot read property 'innerHTML' of null

html垂直对齐输入类型按钮内的文本

php - 为具有屏幕截图功能的 Web 应用程序提供错误报告工具?

javascript - 使用 Protractor 工具使用特定元素定位器捕获图像

javascript - ion-infinite-scroll 在水平和垂直滚动时不起作用

javascript - 如何制作一个执行事件的函数点击jquery

javascript - 不可用的外部资源是否会影响页面加载时间和页面功能?

javascript - 如何编写一个 Protractor 测试来查找 'ng-repeat' 中的第一个元素?