javascript - Angular $scope.var undefined in the controller but present in HTML -
this seems newb question...
i have simple app displays 2 lists of todos , 1 text input field adding new todos in each list.
problem 1: when trying add new todo $scope.todotext undefined in controller.
problem 2: how add new todo item correct list?
code: js
function todoctrl($scope) { $scope.lists = [ {name:'list1', todos:[ {text:'learn angular', done:true}, {text:'build angular app', done:false} ]}, {name:'list2', todos:[ {text:'buy milk', done:false}, {text:'buy fruit', done:false}]} ]; $scope.addtodo = function(listname) { alert($scope.todotext); // trying fix // todo add new todo listname $scope.todotext = ''; }; } html
<div ng-app> <h2>todo</h2> <div ng-controller="todoctrl"> <ul> <li ng-repeat="onelist in lists"> <ul> <hr/> <h2>=== {{onelist.name}} ===</h2> <form ng-submit="addtodo({{onelist.name}})"> <input type="text" ng-model="todotext" size="30" placeholder="add new todo here"> <input type="submit" value="add"> </form> <li ng-repeat="todo in onelist.todos"> <input type="checkbox" ng-model="todo.done"> <span class="done-{{todo.done}}">{{todo.text}}</span> </li> </ul> </li> </ul> </div> </div> jsfiddle here: http://jsfiddle.net/supercobra/v8hxg/
the model variable todotext within scope of ng-repeat , method add in parent scope, cannot access it. can pass collection , new item add method perform addition of new todo this
$scope.addtodo = function(list,todotext) { list.todos.push({text:todotext,done:false}); }; i have updated fiddle fixes.
Comments
Post a Comment