我本来想问这个问题,但我想出了一个解决方案。所以在这一点上,我正在寻找对我的解决方案的批评。
我有一个 static
textarea
和一个input
withng-repeat
指令。当用户在 中键入句子时
textarea
,input
会为句子中的每个单词呈现 a。然后,如果用户更新 any 中的文本,则句子
input
中的相应单词textarea
也会更新(实际上是整个句子都被重新创建了)。
演示:http ://plnkr.co/edit/bSjtOK?p=preview
问题
请记住,我学习 AngularJS 的时间只有 2 周:
- 我是用“角度”的方式写的吗?
- 有什么我可以做得更好的吗?
- 我是否违反了任何禁忌?
缩写代码
HTML
<textarea ng-model="sentence" ng-change="parseSentence()" style="width: 100%; height: 15em;"></textarea>
<input type="text" ng-repeat="w in words" ng-model="w.word" ng-change="buildSentance(w)" />
JavaScript
function WordCtrl($scope, debounce) {
$scope.words = [];
$scope.sentence = 'Hello there how are you today?';
// this is called when the textarea is changed
// it splits up the textarea's text and updates $scope.words
$scope.parseSentence = function() {
var words = $scope.sentence.split(/\s+/g);
var wordObjects = [];
for (var i=0;i<words.length;i++) {
wordObjects.push({word: words[i]});
}
if ((words.length == 1) && (words[0] === '')) {
$scope.words = [];
} else {
$scope.words = wordObjects;
}
};
$scope.parseSentenceDebounced = debounce($scope.parseSentence, 1000, false);
$scope.buildSentance = function(w) {
var words = [];
for (var i=0;i<$scope.words.length;i++) {
var word = $scope.words[i].word;
if (word.replace(/\s+/g,'') !== '') {
words.push(word);
}
}
$scope.sentence = words.join(' ');
// if the user puts a space in the input
// call parseSentence() to update $scope.words
if (w.word.indexOf(' ') > -1) {
$scope.parseSentenceDebounced();
}
}
$scope.parseSentence();
}