0

I am trying to post some data via save but cannot see the data in the browser unless i refresh, the todo.id is showing straight away but not the todo.name

    <body ng-controller="TodoCtrl">
      <div ng-repeat="todo in Todos.record">
           <div>{{todo.id}} : {{todo.name }}</div>
      </div>
      <div>
        <input ng-model="todo.name" />
        <button ng-click="addItem()">Add Item</button>
      </div>
    </body>

var app = angular.module("myApp",['ngResource']);

app.factory("Todo",function($resource){
    return $resource(
        "http://localhost/rest/motors/users?app_name=motors",
        {},
        {
            query: {method: 'GET',isArray: true},
            get: {method: 'GET'},
            save:{method:'POST'}
        }
    )
})

app.controller("TodoCtrl", function ($scope, Todo) {
    "use strict";
    $scope.Todos = Todo.get();
    $scope.addItem = function(){
        Todo.save($scope.todo, function(data){
            $scope.Todos.record.push(data);
            $scope.todo={};
        });
    }
})
kam
  • 425
  • 2
  • 6
  • 24
  • Try adding a $scope.$apply() to do another digest cycle in your Todo.save method. – Christopher Marshall May 30 '14 at 16:13
  • So you're saying after you add a new item, the ID of the new item is displaying but not the name? Are you sure that `data` contains a `name` attribute? Otherwise, try putting a `$scope.$apply()` at the end of your save callback function, but this may not be necessary if angular does this for you already. – Decade Moon May 30 '14 at 16:18
  • Not sure if this is directly related to your problem, but your ng-model="todo.name" is outside the scope of your repeat. Each repeat creates a new scope – tgeery May 30 '14 at 16:23
  • you mean like this => Todo.save($scope.todo, function(data){ $scope.Todos.record.push(data); $scope.todo={}; });$scope.$apply() – kam May 30 '14 at 16:29
  • Decade Moon : i tried using $scope.$apply but doesn't seem to work, yes the ID of the new item shows soon i click the button but the item only shows once the page is refreshed. – kam May 30 '14 at 16:47
  • adding $scope.$apply() gives another Error: $rootScope:inprog Action Already In Progress which mean $digest already in progress – kam May 30 '14 at 16:49

2 Answers2

0

If that code sample is representative of your real code, it's likely a problem that the "input" field that references "todo.name" is OUTSIDE of the ng-repeat loop, so that is defining a model property outside of your "Todos.record" list.

David M. Karr
  • 14,317
  • 20
  • 94
  • 199
  • Hi, yeah... thought input has to be outside the ng-repeat or could end up having lots of textboxes repeating ;) – kam May 30 '14 at 17:08
0

adding &fields=* in the api url solved the issue. eg changed

"http://myexample.com/rest/motors/users?app_name=motors"
 to 
"http://myexample.com/rest/motors/users?app_name=motors&fields=*"

Thanks for help.

kam
  • 425
  • 2
  • 6
  • 24