【问题标题】:Having trouble setting clearing input field AngularJS设置清除输入字段 AngularJS 时遇到问题
【发布时间】:2016-06-29 16:03:08
【问题描述】:

无法设置清除输入字段

我目前正在尝试在添加新指令文本后清除 ng-model="newInstruction.instructionText" 上的输入框。这是我尝试将其重置为空字符串但输入字段未清除的代码。这是为什么?

我已经尝试在 updateInstructionText 函数中记录以下内容:

Console.log (newInstruction) 在控制台中返回 undefined。

Console.log ($scope.newInstruction) 在控制台中返回 undefined。

Console.log (instruction) 返回一个包含指令文本的对象 ex: Object {instructionText: ‘new instruction’}

控制器:

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>

【问题讨论】:

    标签: javascript html angularjs angular-ngmodel


    【解决方案1】:

    简单地做:

    instruction.instructionText = null
    

    由于你是通过name指令访问函数内部的参数(对象),如果你设置为null,你可以清除输入字段

    【讨论】:

    • 我得到 TypeError: Cannot set property 'instructionText' of undefined in console
    【解决方案2】:

    简单地做 $scope.newInstruction.instructionText=null

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 2017-04-09
      • 1970-01-01
      相关资源
      最近更新 更多