AngularJS之DOM實現ng-keyup事件

來源:互聯網
上載者:User
本文主要和大家介紹了AngularJS對動態增加的DOM實現ng-keyup事件樣本,小編覺得挺不錯的,現在分享給大家,也給大家做個參考,希望能協助到大家。

我們經常在網頁中看到這種形式的內容,

用滑鼠點擊一下,就變成了一個input

如果未輸入內容,並且滑鼠離開後,則變回了原來的樣子;如果輸入了內容,即使滑鼠離開,也保持內容不變,此時輸入斷行符號,則新增內容,並清空輸入框。

我在想這個是這麼實現的?想了一下有這麼一個思路:普通情況下這個是一個pp元素,點擊之後變成一個input元素,滑鼠離開則變回原元素。代碼(含詳細注釋版)如下:


window.onload = function () {  // 頁面載入完給id為click-to-add的元素增加onclick方法  document.getElementById("click-to-add").onclick = function () {    // this在這個函數中就是id為click-to-add的元素,將其儲存到變數non_input_type    var non_input_type = this;    // 建立一個input,儲存到變數input_type    var input_type = document.createElement("input");    // 給input添加class和placeholder,這裡我發現class對bootstrap有效    input_type.setAttribute("placeholder", "添加待辦事項");    input_type.className = "form-control";    // 擷取父元素,然後父元素替換Child    this.parentNode.replaceChild(input_type, non_input_type);    // 設定焦點到input框中    input_type.focus();    // 當input失去焦點,即滑鼠點到了別的地方    input_type.onblur = function () {    // 且input中沒有輸入內容時    if (input_type.value.length === 0){      // 再替換回原來的對象      input_type.parentNode.replaceChild(non_input_type, input_type);      }    }  }};

對應的html代碼則很簡單:


  <p>    <p id="click-to-add">      <span>+</span>      <span>添加待辦事項</span>    </p>  </p>

那麼input怎麼響應斷行符號呢?html內建的onkeyup可以很容易做到,在此不示範,可以自行搜尋。而在Angular中,可以給input增加ng-keyup來實現,這個本來也很簡單,但在現在的這個問題中,input不是一開始就有的,而是新產生的,直接使用ng-keyup並不起作用,Angular只會監聽在頁面載入完時的ng方法,新增的則無效,要使新增的DOM也能響應Angular方法,需要對其使用$compile方法,在前文this.parentNode.replaceChild(input_type, non_input_type);這句代碼之前增加以下兩行:


// 增加ng-keyup事件,對應執行send($event)這個函數input_type.setAttribute("ng-keyup", "send($event)");// 對input_type使用$compile方法$compile(input_type)($scope);

接下來還要編寫send方法,如下:


$scope.send = function (e) {  // 不同瀏覽器擷取按鍵代碼不一樣,有的是e.keyCode,有的是e.which  var keycode = window.event?e.keyCode:e.which;  // 斷行符號對應13  if (keycode === 13){    // e.targe就是對應的DOM,這裡擷取到value就按自己的需求去處理了    alert("Add ToDo: " + e.target.value);    e.target.value = "";  }}

示範如下,普通情況下是這樣的:

點擊後變成輸入框:

有內容時,失去焦點也不會變,無內容時則回到普通狀態,按下斷行符號時,則alert內容:

後來我又想了一下,只使用input就可以了,可以修改placeholder的顏色……

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.