angularjs指令名是怎麼回事?

來源:互聯網
上載者:User

標籤:style   http   使用   os   io   strong   檔案   for   

疑惑

查了很多資料,對指令名的介紹都是一筆帶過,只說是駝峰形式. 但是在實際使用時,經常遇到定義的指令名與指令標籤對應不上的情況. 對指令名就感到非常疑惑. 定義時指令名是一種形式,使用時又是一種形式,兩者怎麼關聯對應的?

分析源碼

找不到資料,自己查查angular源碼,一探究竟.

首先在angular.js檔案,找到解析指令名的代碼

switch(nodeType) {  case 1: /* Element */    // use the node name: <directive>    //此處是解析標籤形式的指令    addDirective(directives,        directiveNormalize(nodeName_(node).toLowerCase()), ‘E‘, maxPriority, ignoreDirective);    // iterate over the attributes    for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,             j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {      var attrStartName = false;      var attrEndName = false;      attr = nAttrs[j];      if (!msie || msie >= 8 || attr.specified) {        name = attr.name;        value = trim(attr.value);        // support ngAttr attribute binding        ngAttrName = directiveNormalize(name);        if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {          name = snake_case(ngAttrName.substr(6), ‘-‘);        }        var directiveNName = ngAttrName.replace(/(Start|End)$/, ‘‘);        if (ngAttrName === directiveNName + ‘Start‘) {          attrStartName = name;          attrEndName = name.substr(0, name.length - 5) + ‘end‘;          name = name.substr(0, name.length - 6);        }        //此處是解析屬性形式的指令名        nName = directiveNormalize(name.toLowerCase());        attrsMap[nName] = name;        if (isNgAttr || !attrs.hasOwnProperty(nName)) {            attrs[nName] = value;            if (getBooleanAttrName(node, nName)) {              attrs[nName] = true; // presence means true            }        }        addAttrInterpolateDirective(node, directives, value, nName);        addDirective(directives, nName, ‘A‘, maxPriority, ignoreDirective, attrStartName,                      attrEndName);      }    }

上面一處是解析標籤形式的指令名,調用了directiveNormalize(nodeName_(node).toLowerCase())

另一處是解析屬性形式的指令名,調用了directiveNormalize(name.toLowerCase())

兩處都使用了toLowerCase()

所以解析指令的?第一步:將指令名轉為小寫.?


繼續看directiveNormalize()函數

var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;/** * Converts all accepted directives format into proper directive name. * All of these will become ‘myDirective‘: *   my:Directive *   my-directive *   x-my-directive *   data-my:directive * * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */function directiveNormalize(name) {  return camelCase(name.replace(PREFIX_REGEXP, ‘‘));}

它使用用了name.replace(PREFIX_REGEXP, ‘‘),它的作用是去掉x和data開始的首碼

所以解析指令的第二步: 去掉以x-和data-開頭的首碼(例如 x- x: x_ data- data: data_ 忽略大小寫)


再繼續看camelCase()函數

var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;var MOZ_HACK_REGEXP = /^moz([A-Z])/;var jqLiteMinErr = minErr(‘jqLite‘);/** * Converts snake_case to camelCase. * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */function camelCase(name) {  return name.    replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {      return offset ? letter.toUpperCase() : letter;    }).    replace(MOZ_HACK_REGEXP, ‘Moz$1‘);}

使用了兩個replace替換字元,第二個replace不用管,重點看第一個replace,它是什麼作用?


把它拿出來看看

var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;function camelCase(name) {  return name.    replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {      console.log("_:" + _)      console.log("separator:" + separator)      console.log("letter:" + letter)      return offset ? letter.toUpperCase() : letter;    }).}console.log("----my-directive")console.log(camelCase(my-directive));console.log("----mydirective")console.log(camelCase(my-directive));console.log("----mydirectiveworld")console.log(camelCase(my-directive));/* 輸出內容----my-directive_:-dseparator:-dletter:dmyDirective----mydirectivemydirective----mydirectiveworldmydirectiveworld*/

可以看到第一個replace作用是產生駝峰指令名

所以解析指令的第三步:根據分割符(: - _)標記,將字元轉換為駝峰形式


關於replace函數的說明,可以看看這篇文章

http://yongqing.is-programmer.com/posts/56305.html


更多指令名與指令對應的樣本

以分割符"-"為例mymenu --> mymenu   正確mymenu --> myMenu   錯誤mymenu --> my-Menu  錯誤myMenu --> my-Menu  正確myMenu --> myMenu   錯誤myMenu --> mymenu   錯誤MyMenu --> x-MyMenu 正確MyMenu --> MyMenu   錯誤MyMenu --> mymenu   錯誤myProductsMenu --> my-Products-Menu   正確myProductsMenu --> myProductsMenu     錯誤myProductsMenu --> my-ProductsMenu    錯誤

總結

指令的匹配過程

  1. 將指令名轉換為小寫.

  2. 去掉以x-和data-開頭的首碼(例如 x- x: x_ data- data: data_ 忽略大小寫)

  3. 根據分割符(: - _),轉換為駝峰形式

其實只要注意一點: 匹配過程以定義時的指令名為準,分割符是用來標識駝峰的(angular沒有能力識別單詞,分割符的一個作用是標識駝峰).

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.