angularjs - Angular 1.4 View 封装和 Shadow DOM - 有可能吗?

标签 angularjs polymer encapsulation shadow-dom

出于稳定性原因,我正在将我的应用程序从使用 Polymer 更改为 Angular 1.4。由于我熟悉 Polymer 和 Web 组件(以及 future 对 Angular 2 的使用),我选择使用 Component Pattern 来构建我的应用程序。 .

我已经搜索过,到目前为止只找到this question解决方案是不再维护的 github 存储库。我想知道 Angular 1.4 是否可以进行 View 封装。如果我说错了,具体来说,我的模板指令是否可以有自己的封装样式,就像 Polymer 中所做的那样和 Angular 2 而不依赖 Grunt?

最佳答案

好像确实是这样。我在测试中使用 Angular 1.6,但我能够让影子 DOM 在 Angular 指令(包括绑定(bind))内工作。

这是我的示例代码:

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <meta charset="utf-8">
    <title>Angular 1.x ShadowDOM example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script>
    var app = angular.module('app', []);

    app.controller('myElController', ($scope) => {

    });

    var template = `
    <style>
    :host {
      left: 50%;
      position: fixed;
      top: 50%;
      transform: translate(-50%,-50%);
      border: 1px solid black;
      box-shadow: 4px 4px 4px rgba(0,0,0,.4);
      display: inline-block;
      padding: 6px 12px;
    }

    h3 {
      border-bottom: 1px solid #999;
      margin: 0 -12px 8px;
      padding: 0 12px 8px;
    }

    p {
      margin: 0;
    }
    </style>
        <h3>{{title}}</h3>
      <p>{{info}}</p>
    `;

    app.directive('myEl', ($compile) => {
        return {
          "restrict": "E",
          "controller": "myElController",
          "template": '',
          "scope": {
            "title": "@",
            "info": "@"
          },
          "link": function($scope, $element) {
            console.log('here');
            $scope.shadowRoot = $element[0].attachShadow({mode:'open'});
            $scope.shadowRoot.innerHTML = template;
            $compile($scope.shadowRoot)($scope);
          }
        };
    });
    </script>
  </head>
  <body>
    <div>
      <my-el title="This is a title" info="This is the info of the element"></my-el>
    </div>
    <div class="shell">
      <h3>Outside title (H3)</h3>
      <p>Outside content (P)</p>
    </div>
  </body>
</html>

诀窍是不要为指令设置默认模板。只是我们一个空字符串。然后,在link 函数中,您将创建影子根并将其innerHTML 设置为您的真实模板。然后,您需要在影子根上运行 $compile 将其绑定(bind)回指令的 $scope。

Be aware that this will only work on a browser that natively supports shadow DOM. Any Polyfill will not support real CSS encapsulation. For that it is better to use a form of BEM CSS: http://getbem.com/introduction/

关于angularjs - Angular 1.4 View 封装和 Shadow DOM - 有可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33073728/

相关文章:

html - polymer 如何在图标中包含 svg 文件?

c# - 属性与字段 : Need help grasping the uses of Properties over Fields

php - 为什么方法和属性的可见性很重要?

domain-driven-design - Domen 驱动的架构和用户拼写错误/错误

javascript - 在 AngularJs 中使用两种过滤器过滤一些数据但不起作用

javascript - 麻烦造型扩展 polymer 元素(纸 slider )

javascript - 您如何将状态 401 从 WebAPI 返回到 AngularJS 并包含自定义消息?

javascript - 无法在 javascript/Polymer 中调用我的递归函数

javascript - AngularJS 不显示 json 数据

javascript - 将 Angularjs 服务注入(inject) Controller