Material 使用 Angular JS 的 Design Lite 渲染问题

Material Design Lite rendering problems with Angular JS

我在使用 Material Design Lite (getmdl.io) 时遇到一些问题。我按照 getmdl.io web 中显示的步骤进行安装(实际上我使用的是 bower),但我总是遇到同样的问题,当我在我的 web 中更改 ng-route 时,某些资源不会呈现正确地,我需要重新加载页面以使其正确呈现,例如。

首先我有这个:

然后当我重新加载时,我得到了我想要的:

我无法理解为什么 google 图标或按钮等其他资源可以正常工作,但导航栏上的菜单按钮和其他此类资源需要重新加载页面才能正确呈现。

我尝试使用托管方法和 bower 方法包​​含库。

知道发生了什么吗?

MDL 等库的工作方式是使用 DOMContentLoaded 事件等待页面加载,扫描页面以查找输入元素并使用 JavaScript 对其进行操作,以便它们可以注入位和零件需要与他们的组件一起工作。这在静态网站上运行良好,但 DOMContentLoaded 事件仅触发 一次,因此当 Angular 执行页面转换时,DOM 更改而不会MDL知道了。

Material Design Lite 在其常见问题解答中有一节关于 using MDL on dynamic websites:

Material Design Lite will automatically register and render all elements marked with MDL classes upon page load. However in the case where you are creating DOM elements dynamically you need to register new elements using the upgradeElement function. Here is how you can dynamically create the same raised button with ripples shown in the section above:

<div id="container"/>
<script>
  var button = document.createElement('button');
  var textNode = document.createTextNode('Click Me!');
  button.appendChild(textNode);
  button.className = 'mdl-button mdl-js-button mdl-js-ripple-effect';
  componentHandler.upgradeElement(button);
  document.getElementById('container').appendChild(button);
</script>

当然,这在您的情况下可能不是很容易做到,因为您必须手动查找每个新元素并对其调用 upgradeElement

通常,Angular 不使用这种基于事件的 DOM 操作,而是使用指令来启动 DOM 更改。考虑使用构建为与 Angular 互操作的库,例如 Angular Material.

我在我的代码中传递了这个函数

angular.module('app', ['ngRoute']).

    run(function($rootScope, xxxx, xxx){
        $rootScope.$on('$viewContentLoaded', function(event, next) {
            componentHandler.upgradeAllRegistered();
        });
    });

效果很好!祝你好运..