AngularFire 3-way data binding does not update firebase when checkbox is changed

I am developing a simple todo application with Angular and Firebase using the AngularFire module.

So, I have a boolean attribute in my model represented by a checkbox in the template, the problem is that I'm trying to use the three-way data binding from AngularFire using the method $bindso that all changes are synchronized (firebase, DOM and ng-model data), but firebase data is not updated when I check the box.

Here is my controller where I use the AngularFire method $bind:

angular.module('singularPracticeApp')
  .controller('TodoCtrl', ['$scope', 'TodoService', function ($scope, todoService) {
    $scope.todos = todoService;

    $scope.todos.$bind($scope, 'todo.done');

    $scope.addTodo = function () {
      $scope.todos.$add({text: $scope.todoText, done:false});
      $scope.todoText = '';
    };

    $scope.remaining = function () {
      var count = -11;
      angular.forEach($scope.todos, function(todo){
        count += todo.done? 0 : 1;
      });
      return count;
    };

    $scope.clear = function (id) {
      $scope.todos.$remove(id);
    };
  }]);

And here is the tempalte file:

<div ng-controller="TodoCtrl">
  <h4>Task runner</h4>
  <span>{{remaining()}} todos left.</span>
  <ul>
    <li ng-repeat="(id, todo) in todos">
      <input type="checkbox" ng-model="todo.done">
      <span ng-if="todo.done" style="color: #ddd;">{{todo.text}}</span>
      <span ng-if="todo.done == false">{{todo.text}}</span>
      <small ng-if="todo.done"><a href="" ng-click="clear(id)">clear</a></small>
    </li>
  </ul>
  <form ng-submit="addTodo()">
    <input type="text" ng-model="todoText" placeholder="New todo item">
    <input type="submit" class="btn btn-primary" value="add">
  </form>
</div>  

Am I missing something? Is it really possible to do this job with a simple checkbox?

Thanks in advance.

+4
1

todoService , . , todoService $firebase, todos, . , .

, , :

TodoCtrl

, TodoCtrl, ng-repeat. ng-repeat .

Ng-repeat .

. , . , ng-repeat = "todo in todos", todo .

, ng-repeat todo.

$scope.todos.[$todo].done, $scope.todos. $scope.todos .

$scope.todos

$bind, $scope.todos $scope.todos.todo.done. , , . , , , , :

todoService.$bind($scope, 'todos');

todos, $save $bind:

$scope.todos = todoService;

<input type="checkbox" ng-model="todo.done" ng-change="$parent.todos.$save(id)">

:

angular.module('singularPracticeApp')
   .service('todoService', function($firebase) {
      return $firebase( new Firebase(URL_TO_TODOS_LIST) );
   });
   .controller('TodoCtrl', function($scope, todoService) {
      todoService.$bind($scope, 'todos');

      $scope.addTodo = function () {
         $scope.todos.$add({text: $scope.todoText, done:false});
         $scope.todoText = '';
      };

      /** ... and so on ... **/      
   });
+9

Source: https://habr.com/ru/post/1523836/


All Articles