我正在用jQuery開發一個類似todo的應用程序,但我想切換到Angular。是否可以在按鍵之後但在鍵控之前更新模型?
有一個用於添加新項目的輸入字段,但只要在該輸入中鍵入任何內容,關鍵筆劃及其後的關鍵筆劃就會有效地移至現有項目組中的新項目。這意味着新的項目輸入文本框始終保持爲空。更好地顯示解釋:
http://jsfiddle.net/29Z3U/4/(許多細節已刪除,但我所指的應用程序的方面是演示)。
<h1>Song List</h1>
<form id="songs">
<ul id="sortable_songs"></ul>
</form>
<ul id="new_song">
<script id="song_form_template" type="text/x-handlebars-template">
<li class="song" id="{{song_id}}">
<input type="text" placeholder="enter song" autofocus />
</li>
</script>
</ul>
一些jQuery的:
var template = Handlebars.compile($('#song_form_template').html()),
counter = (function(){var i=0; return function(){return ++i};})(),
cloneNewSong = function(){
var count = counter(),
templateVals = {song_id: 'song_' + count};
$('ul#new_song').append(template(templateVals));
},
addSong = function(event){
//exclude certain keys here
cloneNewSong();
container = $(event.target).closest('li.song');
container.appendTo('ul#sortable_songs');
$(event.target)
.removeAttr('placeholder')
.focus(); //what I just typed disappears without this! why?
};
$('ul#new_song').on('keypress', 'input', addSong);
cloneNewSong();
注意的是,新的項目輸入文本框始終保持空,重點表現爲它應該這樣你就可以繼續輸入而中斷。
應用程序代碼變得冗長,我甚至還沒有試圖顯示從JSON派生的歌曲的現有列表。當然,在Angular中,ngRepeat使這一切變得簡單。然而,我在一個角版本嘗試不起作用:http://plnkr.co/edit/xsGRiHFzfsVE7qRxgY8d?p=preview
<!DOCTYPE html>
<html ng-app="songListApp">
<head>
<script src="//code.angularjs.org/1.2.7/angular.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body ng-controller="songListController">
<h1>Song List</h1>
<ul id="songs">
<li ng-repeat="song in songs">
<input type="text" ng-model="song.song_name" />
</li>
</ul>
<form>
<input
ng-keypress="newSong(new_song)"
ng-model="new_song.title"
placeholder="enter song" autofocus
/>
</form>
</body>
</html>
JS:
var myapp = angular.module('songListApp', []);
myapp.controller('songListController', function($scope){
songs = [
{"song_name":"song 1","more_info":""},
{"song_name":"song 2","more_info":""},
{"song_name":"song 3","more_info":""}
];
$scope.songs = songs;
$scope.newSong = function(new_song){
var song = {"song_name": new_song.title, "more_info":""};
songs.push(song);
new_song.title = '';
};
});
即使解決重點管理的問題之前,我注意到角模型的更新總是落後通過一次擊鍵。我認爲這是因爲按鍵事件發生了before the character is inserted into the DOM。
我意識到,從按鍵切換到按鍵會改變一些東西,但最初的設計是基於按鍵的響應。
我想自定義指令綁定到input event但是我所希望的東西不規矩:http://plnkr.co/edit/yjdbG6HcS3ApMo1T290r?p=preview
我注意到,在angularjs.org第一個代碼示例(基本無控制器綁定)沒有按似乎沒有受到我所擁有的問題的影響 - 示例模型會在發佈密鑰之前更新。
I」我在IE11和Chrome 32上試過了;它僅適用於輸入第一首歌 - 可以再看一次嗎? – KnewB
@KnewB這部分沒有工作。鉻被測試。 IE11 - 我沒有IE – michael
@KnewB對不起。這是發佈之前的最新優化。函數名稱必須是'createNewSong'而不是'newSong'。 – michael