Huy Do
Huy Do

Reputation: 470

need clearly explanation about error in angularjs

I am a newbie to Angularjs. I often get this error when I try to push an object to an array.
I try many ways but I don't know what's wrong with it.

It repeatedly gets error: $scope.todo is undefined.

Here is my code (link at http:// plnkr.co/edit/rvhLhuwlR7UsYtaLhKjh)

When I add $scope.todo = {}; it can't get the title I enter and it push blank title. Please explain in detail and clearly for me so that I can understand more about $scope and form input in controller. Thanks

this is my module code

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 = '';
    };
  });

Upvotes: 0

Views: 186

Answers (2)

Parv Sharma
Parv Sharma

Reputation: 12705

as your code seems

$scope.addTodo = function(){
      $scope.todos.push({title: $scope.todo.title});
      $scope.todo.title = '';
    };

in the line $scope.todos.push({title: $scope.todo.title}); you still dont have $scope.todo.title defined because you are defining it on the next line.

change the code to.

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 = {};
    };
  }]);

i have edited your plunker here have a look. i have made changes to your HTML and script.js http://plnkr.co/edit/Z1fg0rg6cUbsJJOy9wie?p=preview

Upvotes: 1

Jordan
Jordan

Reputation: 2049

The problem is $scope.todo isn't defined yet.

Under the $scope.addTodo function just add:

$scope.todo = {};

$scope.todo.title = '';

After the function. Then it is initialized.

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 = '';
});

Upvotes: 1

Related Questions