javascript - 不能使用字母 x 开始 Angular 中的 html 属性

标签 javascript angularjs

我注意到 Angular 1.5.6 组件有一些非常奇怪的地方。我有一个名为 scale 的组件。我称之为:

<scale x-scale="xScale"></scale>

在我的 Controller 中:

$scope.xScale = 'lin'.

还有我的组件定义:

angular
    .module('myapp')
        .component('scale', {
            templateUrl: 'analyse/components/scales/scale.tpl.html',
            controller: function(){
                console.log('in controller and this is ', this);

            },
            bindings: {
              xScale: '='
            },
    });

控制台日志输出undefined。

但是如果我改变x-scaler-scale在我的模板和xScale在绑定(bind)到 rScale ,突然它起作用了。事实上,如果我用任何其他字母替换 x,它似乎有效。这是为什么?

最佳答案

它在 documentation 中对于指令

Normalization

Angular normalizes an element's tag and attribute name to determine which elements match which directives.
We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel).

However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model).

The normalization process is as follows:

  1. Strip x- and data- from the front of the element/attributes.
  2. Convert the :, -, or _ -delimited name to camelCase.

因此 Angular 从任何属性名称的前面去除 x- 以对其进行规范化,这样做是因为常规数据属性(以 data- 开头)和x-属性,以 x- 开头,在 HTML 5 中有效。

HTML5 specification指出

Attribute names beginning with the two characters "x-" are reserved for user agent use and are guaranteed to never be formally added to the HTML language.

它还指出

For markup-level features that are intended for use with the HTML syntax, extensions should be limited to new attributes of the form "x-vendor-feature", where vendor is a short string that identifies the vendor responsible for the extension, and feature is the name of the feature.

x- 属性不常使用,但如上所述,它们是为浏览器 vendor 保留的,您不应该使用它们,而应该使用数据属性,顺便说一下,Angular 也会为你删除 data- 部分,所以这些

<scale data-scale="scale"></scale>
<scale x-scale="scale"></scale>
<scale scale="scale"></scale>

当你做的时候都是“一样的”

$scope.scale = 'lin'.

关于javascript - 不能使用字母 x 开始 Angular 中的 html 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40444167/

相关文章:

javascript - 如何使用 ajax 显示多个字符串的串联? (或不)

javascript函数是对象吗?

javascript - 如何在内部 v-tooltip 悬停时关闭外部 v-tooltip

javascript - AngularJS |在加载之前处理路由

javascript - 使用 "this"语法时如何访问 Controller 中的 "the controller as"?

javascript - 正则表达式:包含字符串精确 n 次

javascript - Canvas 旋转 - 固定背景,移动前景

javascript - 通知权限总是被拒绝

javascript - IE 中的 Object.assign 解决方法

javascript - 当模型执行ajax请求时使用什么模式来观察