读取NFC标签时调用AngularJS函数?

时间:2015-08-07 09:59:50

标签: javascript angularjs cordova ionic nfc

我使用Ionic和phonegap-nfc编写了一个小型演示应用程序,它可以读取NFC标签中的唯一ID。

现在,我正在尝试创建一个显示先前读取事件的列表。应该在此列表中添加一个事件,以便读取标记。

我有一个可以添加事件的列表。代码如下所示:

<ion-view view-title="Usage History">
  <ion-content>
    <button class="button button-icon" ng-click="newTask()">
      <i class="icon ion-compose"></i>
    </button>
    <ion-list>
      <ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap" href="#/tab/tasks/{{task.id}}">
        <img ng-src="{{task.pic}}">
        <h2>{{task.name}}</h2>
        <p>{{task.lastText}}</p>
        <i class="icon ion-chevron-right icon-accessory"></i>

        <ion-option-button class="button-assertive" ng-click="remove(task)">
          Delete
        </ion-option-button>
      </ion-item>
    </ion-list>
    <script id="new-task.html" type="text/ng-template">

    <div class="modal">

    <!-- Modal header bar -->
    <ion-header-bar class="bar-secondary">
    <h1 class="title">New Task</h1>
    <button class="button button-clear button-positive" ng-click="closeNewTask()">Cancel</button>
    </ion-header-bar>

    <!-- Modal content area -->
    <ion-content>

    <form ng-submit="createTask(task)">
    <div class="list">
    <label class="item item-input">
    <input type="text" placeholder="What do you need to do?" ng-model="task.name">
    </label>
    </div>
    <div class="padding">
    <button type="submit" class="button button-block button-positive">Create Task</button>
    </div>
    </form>

    </ion-content>

    </div>

    </script>
  </ion-content>
</ion-view>

控制器如下所示:

.controller('TasksCtrl', function($scope, $ionicModal) {

  $scope.tasks= [];

  // Create and load the Modal
  $ionicModal.fromTemplateUrl('new-task.html', function(modal) {
    $scope.taskModal = modal;
  }, {
    scope: $scope,
    animation: 'slide-in-up'
  });

  // Called when the form is submitted
  $scope.createTask = function(task) {
    $scope.chats.push({
      name: task.name
    });
    $scope.taskModal.hide();
    task.name= "";
  };

  // Open our new task modal
  $scope.newTask = function() {
    $scope.taskModal.show();
  };

  // Close the new task modal
  $scope.closeNewTask = function() {
    $scope.taskModal.hide();
  };

  $scope.remove = function(task) {
    tasks.remove(task);
  };
})

所有这一切都很好。您有一个按钮,可以打开一个模态,您可以在其中添加任务。按下按钮关闭模态,任务现在在列表中。

但是,我想在读取NFC标签时自动创建任务。我是一个使用Angular的初学者,所以我不知道如何用与phonegap-nfc相对应的NFC动作替换“ng-click”动作。

NFC事件的控制器如下所示:

.controller('MainController', function ($scope, nfcService) {

  $scope.tag = nfcService.tag;
  $scope.clear = function() {
    nfcService.clearTag();
  };
})

.factory('nfcService', function ($rootScope, $ionicPlatform) {
  var tag = {};
  $ionicPlatform.ready(function() {
    nfc.addTagDiscoveredListener(function (nfcEvent) {
      console.log(JSON.stringify(nfcEvent.tag, null, 4));
      $rootScope.$apply(function(){
        angular.copy(nfcEvent.tag, tag);
        // if necessary $state.go('some-route')
      });
    }, function () {
      console.log("Listening for tags.");
    }, function (reason) {
      alert("Error adding NFC Listener " + reason);
    });

    nfc.addMimeTypeListener('', function (nfcEvent) {
      console.log(JSON.stringify(nfcEvent.tag, null, 4));
      $rootScope.$apply(function(){
        angular.copy(nfcEvent.tag, tag);
        // if necessary $state.go('some-route')
      });
    });
  });
  return {
    tag: tag,
    clearTag: function () {
      angular.copy({}, this.tag);
    }
  };
});

我该怎么做?

1 个答案:

答案 0 :(得分:2)

你的nfcService已经在监听tagDiscovered事件,所以你只需让TaskCtrl知道发生了什么事。要做到这一点,你有几个选择

  1. 使用events / broadcast
  2. 一个。在nfcService

    function CalendarCtrl($mdDialog, $http, $rootScope, $timeout, User, Auth, UserService) {
      var ctrl = this;
    
      angular.extend(ctrl, {
        getCurrentUser: Auth.getCurrentUser,
        getUsers: UserService.getUsers,
        isAdmin: Auth.isAdmin,
        addUser: addUser,
        users: UserService.userList,
        newUser: {}
      });
    
      init();
    
      function init() {
        ctrl.getUsers();
        initNewUser();
      }
    
      function initNewUser() {
        ctrl.newUser = { email: "", role: "" };
      }
    
      function addUser() {
        UserService.addUser(ctrl.newUser)
        .success(function(newUser){
          console.log("Controller: user has been added: ", newUser);
        })
        .error(function(err){
          console.log("Controller: Add user error: ", err);
        })
        .finally(function() {
          initNewUser();
        });
      }
    }
    

    湾在TaskCtrl

    $rootScope.$emit('tagFound', tag);
    
    1. 注册回调函数
    2. 一个。在nfcService中添加功能

      $rootScope.$on('tagFound', function(tag) {
          newTask();
      });
      

      湾在taskCtrl

      var cb = null;
      this.registerListener = function (callback){
          this.cb = callback;
      }
      // inside addTagDiscoveredListener
      ...
      cb.call(tag)
      
      1. 转到新状态

        //在nfcService中 $ state.go( '/任务/添加');

      2. 我通常会做选项2,但不要忘记取消注册以解除对垃圾收集的阻止。服务不应该关心国家,所以选项3不是最好的方式imho