angular.js - 请问angular中定义directive后,createElement是必须的吗?

浏览:53日期:2023-01-23

问题描述

如下代码所示,定义了directive layoutHeader,按照我的理解,直接在html中引用<layout-header></layout-header>就可以了。想问下,这里的

document.createElement(’layout-header’); 有什么作用?是必须的吗?

原代码如下:

angular.module(’app’).directive(’layoutHeader’, function () { return { restrict: ’E’, scope: {}, templateUrl: ’components/layout/header.html’, controller: ’LayoutHeaderCtrl’ };});document.createElement(’layout-header’);

问题解答

回答1:

这只是在做兼容处理,ie8无法识别自定义的元素,但是用js创建的反而可以识别。

回答2:

document.createElement这是浏览器提供的js方法。可以用代码生成dom。你直接在html中引用就行了,不必要非用代码的方式创建。

回答3:

直接在html代码里面使用<layoutHeader></layoutHeader>就可以了。

回答4:

这个是示例代码吧?

其实就是在 js 里面创建一下这个 element 而已,在 html 直接写是一样的。

= = 其实有点好奇这是什么入门教材。。

回答5:

正如xiaohe 所说,是为了兼容性而做的处理。参考:http://www.oschina.net/translate/angularjs-ie-compatibility?print

如果你必需要用自定义元素标记,然后你必须采取以下步骤以确保IE8及之前版本都能用:<!doctype html><html xmlns:ng='http://angularjs.org' ng-app='optionalModuleName'><head> <!--[if lte IE 8]> <script> document.createElement(’ng-include’); document.createElement(’ng-pluralize’); document.createElement(’ng-view’);// Optionally these for CSS document.createElement(’ng:include’); document.createElement(’ng:pluralize’); document.createElement(’ng:view’); </script> <![endif]--></head><body></body></html>

相关文章: