jashuang1130
jashuang1130

Reputation: 429

Having trouble setting clearing input field AngularJS

Having trouble setting clearing input field

I’m currently trying to clear the input box on ng-model="newInstruction.instructionText" after an new instruction text has been added. Here is the code where I tried to reset it to empty string but input field didn't clear. Why is that?

I’ve tried console logging the following in updateInstructionText function:

Console.log (newInstruction) returns undefined in console.

Console.log ($scope.newInstruction) returns undefined in console.

Console.log (instruction) returns a object with instruction text inside ex: Object {instructionText: ‘new instruction’}

Controller:

angular.module('app').controller('InstructionController', function($scope, $http, NgTableParams, $filter) {
  $scope.initList = function() {
    $scope.getRemoteInstructions = function(typed) {
      $http.get("/api/instructions?searchInstructionText=" + typed).then(function(response) {
        $scope.instructionChoices = _.map(response.data, function(instruction) {
          instruction.instructionText;
        });
      });
    };
    $scope.updateInstructionText = function(instruction) {
      var instructionPromise;
      if (instruction.id) {
        instructionPromise = $http.put("api/instructions/" + instruction.id, instruction);
      } 
      else {
        instructionPromise = $http.post("/api/instructions", instruction);
      }

      $scope.newInstruction = '';
      $instruction = '';

      instructionPromise.then(function(response) {
        $('#instructionModal').closeModal();
        $scope.instructionTable.reload();
      });
    };
  };
});

HTML

<div class="container-fluid" ng-init="initList()">
  <div class="row">
      <h3>Total Instructions: {{totalInstructions}}</h3>
      <table class="striped highlight bordered" ng-table="instructionTable" show-filter="true">
        <tr>
          <td class="input-field">
            <input placeholder="Enter New Instruction Text" ng-model="newInstruction.instructionText" type="text">
          </td>
          <td>
            <a class="waves-effect waves-light btn" ng-click="updateInstructionText(newInstruction)">Add</a>
          </td>
        </tr>
      </table>
    </div>
  </div>
  <ng-include src="'/views/modals/instructionModal.html'"></ng-include>
</div>

Upvotes: 1

Views: 41

Answers (2)

Shobhit Walia
Shobhit Walia

Reputation: 496

Simply do $scope.newInstruction.instructionText=null

Upvotes: 0

Rahul Arora
Rahul Arora

Reputation: 4533

Simply do:

instruction.instructionText = null

Since you are accessing the argument (object) inside the function with name instruction, if you set this to null, you can clear the input field

Upvotes: 1

Related Questions