在函数 $scope.addTodo() 中,我的浏览器仅在 $scope.todos 数组的第一个条目上评估 if 语句。创建单个待办事项后,我现在可以推送空白待办事项,即使这不是预期的结果。也很奇怪的是,如果我将 if 语句从
if ($scope.formTodoText != null)
至
if ($scope.formTodoText != "")
然后我可以提交一个空白的待办事项,但只能提交一次。提交初始空白待办事项后,评估就没有问题了。
<!DOCTYPE html>
<html ng-app>
<head>
<script src="http://documentcloud.github.io/underscore/underscore-min.js"></script>
<script src="http://code.jquery.com/jquery.min.js"></script>
<link href="http://twitter.github.io/bootstrap/assets/css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="http://twitter.github.io/bootstrap/assets/css/bootstrap-responsive.css" rel="stylesheet" type="text/css" />
<script src="http://twitter.github.io/bootstrap/assets/js/bootstrap.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style type="text/css">
.done-true {
text-decoration: line-through;
color: grey;
}
</style>
</head>
<body>
<div ng-controller="TodoCtrl" class="container">
<h2>Total Todos: {{getTotalTodos()}}</h2>
<ul class="unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</li>
</ul>
<form class="form-horizontal">
<input type="text" ng-model="formTodoText" ng-model-instant>
<button class="btn" ng-click="addTodo()"><i class="icon-plus"></i>Add</button>
</form>
<button class="btn-large" ng-click="clearCompleted()"> <i class="icon-trash"></i> Clear</button>
</div>
<script type="text/javascript">
function TodoCtrl($scope) {
$scope.todos = [
{text: 'Learn angular', done: false},
{text: 'Build an app', done: false},
{text: 'Design UI', done: false}
];
$scope.getTotalTodos = function() {
return $scope.totalTodos = $scope.todos.length;
};
$scope.clearCompleted = function () {
$scope.todos = _.filter($scope.todos, function (todo) {
return !todo.done;
});
};
$scope.addTodo = function() {
if ($scope.formTodoText != null) {
$scope.todos.push({text:$scope.formTodoText, done: false});
$scope.formTodoText = "";
}
};
}
</script>
</body>
</html>