如何在一个功能中使用多个ng-model?

时间:2016-02-16 04:49:40

标签: javascript html angularjs indexeddb

大家好我在Angular js中使用索引数据库创建数据库。我的任务是将数据保存到数据库中,我的问题是我们可以在一个函数中使用多个ng-model吗?让我告诉你我的代码,以便明确。

的index.html

<!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
  <script data-require="bootstrap@3.1.1" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
  <script data-require="angular.js@1.2.13" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js"></script>
  <script data-require="angular.js@1.2.13" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular-animate.js"></script>
  <link data-require="bootstrap-css@3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
  <link rel="stylesheet" href="style.css" />
  <script src="app.js"></script>
  </head>

  <body>
    <div data-ng-app="indexDBSample" data-ng-controller="TodoController as vm">
      <table>
        <tr data-ng-repeat="todo in vm.todos">
          <td>{{todo.text}}</td>
          <td>[<a href="#" data-ng-click="vm.deleteTodo(todo.id)">X</a>]</td>
        </tr>
      </table>
      <br />
      <input type="text" data-ng-model="vm.todoText" name="todo" placeholder="textbox1" style="width: 200px;" />
      <input type="text" data-ng-model="vm.todoText1" name="todo" placeholder="textbox2" style="width: 200px;" />
      <input type="text" data-ng-model="vm.todoText2" name="todo" placeholder="textbox3" style="width: 200px;" />
      <input type="button" value="Add" data-ng-click="vm.addTodo()" />
      <input type="button" value="Refresh" data-ng-click="vm.refreshList()" />
    </div>
  </body>

</html>

的script.js

var app = angular.module('indexDBSample', []);

app.factory('indexedDBDataSvc', function($window, $q){
  var indexedDB = $window.indexedDB;
  var db=null;
  var lastIndex=0;

  var open = function(){
    var deferred = $q.defer();
    var version = 1;
    var request = indexedDB.open("todoData", version);

    request.onupgradeneeded = function(e) {
      db = e.target.result;

      e.target.transaction.onerror = indexedDB.onerror;

      if(db.objectStoreNames.contains("todo")) {
        db.deleteObjectStore("todo");
      }

      var store = db.createObjectStore("todo",
        {keyPath: "id"});
    };

    request.onsuccess = function(e) {
      db = e.target.result;
      deferred.resolve();
    };

    request.onerror = function(){
      deferred.reject();
    };

    return deferred.promise;
  };

  var getTodos = function(){
    var deferred = $q.defer();

    if(db === null){
      deferred.reject("IndexDB is not opened yet!");
    }
    else{
      var trans = db.transaction(["todo"], "readwrite");
      var store = trans.objectStore("todo");
      var todos = [];

      // Get everything in the store;
      var keyRange = IDBKeyRange.lowerBound(0);
      var cursorRequest = store.openCursor(keyRange);

      cursorRequest.onsuccess = function(e) {
        var result = e.target.result;
        if(result === null || result === undefined)
        {
          deferred.resolve(todos);
        }
        else{
          todos.push(result.value);
          if(result.value.id > lastIndex){
            lastIndex=result.value.id;
          }
          result.continue();
        }
      };

      cursorRequest.onerror = function(e){
        console.log(e.value);
        deferred.reject("Something went wrong!!!");
      };
    }

    return deferred.promise;
  };

  var deleteTodo = function(id){
    var deferred = $q.defer();

    if(db === null){
      deferred.reject("IndexDB is not opened yet!");
    }
    else{
      var trans = db.transaction(["todo"], "readwrite");
      var store = trans.objectStore("todo");

      var request = store.delete(id);

      request.onsuccess = function(e) {
        deferred.resolve();
      };

      request.onerror = function(e) {
        console.log(e.value);
        deferred.reject("Todo item couldn't be deleted");
      };
    }

    return deferred.promise;
  };

  var addTodo = function(todoText){
    var deferred = $q.defer();

    if(db === null){
      deferred.reject("IndexDB is not opened yet!");
    }
    else{
      var trans = db.transaction(["todo"], "readwrite");
      var store = trans.objectStore("todo");
      lastIndex++;
      var request = store.put({
        "id": lastIndex,
        "text": todoText
      });

      request.onsuccess = function(e) {
        deferred.resolve();
      };

      request.onerror = function(e) {
        console.log(e.value);
        deferred.reject("Todo item couldn't be added!");
      };
    }
    return deferred.promise;
  };

  return {
    open: open,
    getTodos: getTodos,
    addTodo: addTodo,
    deleteTodo: deleteTodo
  };

});

app.controller('TodoController', function($window, indexedDBDataSvc){
  var vm = this;
  vm.todos=[];

  vm.refreshList = function(){
    indexedDBDataSvc.getTodos().then(function(data){
      vm.todos=data;
    }, function(err){
      $window.alert(err);
    });
  };

  vm.addTodo = function(){
    indexedDBDataSvc.addTodo(vm.todoText).then(function(){
      vm.refreshList();
      vm.todo="";

    }
    , function(err){
      $window.alert(err);
    });
  };



  vm.deleteTodo = function(id){
    indexedDBDataSvc.deleteTodo(id).then(function(){
      vm.refreshList();
    }, function(err){
      $window.alert(err);
    });
  };

  function init(){
    indexedDBDataSvc.open().then(function(){
      vm.refreshList();
    });
  }

  init();
});

我使用了三个具有三个不同输入区域的ng模型,但我需要的是在一个函数中使用所有三个ng模型,即

    vm.addTodo = function(){
    indexedDBDataSvc.addTodo(vm.todoText).then(function(){
      vm.refreshList();
      vm.todo="";

    }
    , function(err){
      $window.alert(err);
    });
  };

获得三种不同的输出。请帮助我,因为我是angular.js的新手

这是我的傻瓜:http://plnkr.co/edit/3yM2j9Dgv5FzEP2L9pYH?p=preview

1 个答案:

答案 0 :(得分:1)

将表单中的输入绑定为:

<form name="my_form">
      <input type="text" data-ng-model="vm.todoText" name="todo" placeholder="textbox1" style="width: 200px;" />
      <input type="text" data-ng-model="vm.todoText1" name="todo" placeholder="textbox2" style="width: 200px;" />
      <input type="text" data-ng-model="vm.todoText2" name="todo" placeholder="textbox3" style="width: 200px;" />
       <button type="button" value="Add" data-ng-Click="vm.addTodo(vm)">Add</button>
       <button type="button" value="Refresh" data-ng-Click="vm.refreshList()">Refresh</button>
      </form>

在app.js中,在您的函数中,您可以从data-ng-model获取所有数据。

vm.addTodo = function(vm){
    alert(angular.toJson(vm));
   console.log(angular.toJson(vm.todoText));//check the value in console
   console.log(angular.toJson(vm.todoText1));
   console.log(angular.toJson(vm.todoText2));//you can use the value as vm.todoText,vm.todoText1 and so on.
    indexedDBDataSvc.addTodo(vm.todoText).then(function(){
      vm.refreshList();
      vm.todo="";

    }
    , function(err){
      $window.alert(err);
    });
  };

其余逻辑取决于您对数据所做的任何事情。

更新:根据您的评论需要。使用刷新按钮检查您的数据添加。在原始代码中传递vm,在控制器部分创建冲突,因此我将ng模型更改为形式,以便我可以得到确切的模型值。

<form name="my_form">
      <input type="text" data-ng-model="form.todoText" name="todo" placeholder="textbox1" style="width: 200px;" />
      <input type="text" data-ng-model="form.todoText1" name="todo" placeholder="textbox2" style="width: 200px;" />
      <input type="text" data-ng-model="form.todoText2" name="todo" placeholder="textbox3" style="width: 200px;" />
       <button type="button" value="Add" data-ng-Click="vm.addTodo(form)">Add</button>
       <button type="button" value="Refresh" data-ng-Click="vm.refreshList()">Refresh</button>
      </form>

app.js

 vm.addTodo = function(vm){
    angular.forEach(vm,function(key,value){
    indexedDBDataSvc.addTodo(key).then(function(){
      $window.location.reload();
      vm.todo="";

    }
    , function(err){
      $window.alert(err);
    });
    });
  };

查看此plunkr:http://plnkr.co/edit/xyR2W1GpylMXofIKi1BR?p=preview