我是Angularjs的新手。当我尝试将对象推送到数组时,我经常会遇到此错误
我尝试了很多方法,但我不知道它有什么问题。
它反复出错:$ scope.todo未定义。
Here is my code(链接在http:// plnkr.co/edit/rvhLhuwlR7UsYtaLhKjh)
当我添加$ scope.todo = {};它无法获得我输入的标题,它会推送空白标题。
请详细解释清楚,以便我能够更好地了解控制器中的$ scope和form输入。
感谢
这是我的模块代码
angular.module('todoApp',['ionic'])
.controller('todoCtrl', function($scope){
$scope.todos = [
{title: "Go to the cinema"},
{title: "Take some books"},
{title: "Check out booking room"}
];
$scope.addTodo = function(){
$scope.todos.push({title: $scope.todo.title});
$scope.todo.title = '';
};
});
答案 0 :(得分:1)
问题是$ scope.todo还没有定义。
在$ scope.addTodo函数下添加:
$ scope.todo = {};
$ scope.todo.title ='';
功能完成后。然后它被初始化。
angular.module('todoApp',['ionic'])
.controller('todoCtrl', function($scope){
$scope.todos = [
{title: "Go to the cinema"},
{title: "Take some books"},
{title: "Check out booking room"}
];
$scope.addTodo = function(){
$scope.todos.push({title: $scope.todo.title});
$scope.todo.title = '';
};
$scope.todo = {}
$scope.todo.title = '';
});
答案 1 :(得分:1)
,因为您的代码似乎
$scope.addTodo = function(){
$scope.todos.push({title: $scope.todo.title});
$scope.todo.title = '';
};
行$scope.todos.push({title: $scope.todo.title});
中的你还没有定义$ scope.todo.title,因为你是在下一行定义的。
将代码更改为。
angular.module('todoApp',['ionic'])
.controller('todoCtrl', ['$scope', function($scope){
$scope.todo = {};
$scope.todos = [
{title: "Go to the cinema"},
{title: "Take some books"},
{title: "Check out booking room"}
];
$scope.addTodo = function(){
$scope.todos.push({title: $scope.todo.title});
$scope.todo = {};
};
}]);
我已经编辑了你的plunker here了解一下。 我已经对你的HTML和script.js进行了更改 http://plnkr.co/edit/Z1fg0rg6cUbsJJOy9wie?p=preview