【发布时间】:2014-01-21 03:45:08
【问题描述】:
我正在使用 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 让这一切变得简单。但是,我对 Angular 版本的尝试不起作用: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 = '';
};
});
在解决焦点管理问题之前,我注意到 Angular 模型的更新总是滞后一键。我认为这是因为按键事件发生before the character is inserted into the DOM。
我意识到从 keypress 切换到 keyup 会改变一些事情,但最初的设计是基于 keypress 的响应性。
我尝试了一个自定义指令来绑定到 input event,但事情并没有像我希望的那样运行:http://plnkr.co/edit/yjdbG6HcS3ApMo1T290r?p=preview
我注意到 angularjs.org 上的第一个代码示例(没有控制器的基本绑定)似乎没有遇到我遇到的问题 - 示例模型在释放密钥之前更新。
【问题讨论】:
标签: angularjs angularjs-ng-repeat