簡體   English   中英

確定哪個輸入字段觸發ng-change?

[英]Identify which input field trigger ng-change?

我有2個輸入字段,並且我希望有一個ng-change函數將這些值之一存儲在chrome.storage.local

<input type="text" ng-model="mod1" ng-change="inputChange()" ng-model-options="{ debounce: 250 }">
<input type="text" ng-model="mod2" ng-change="inputChange()" ng-model-options="{ debounce: 250 }">

控制器中的功能與此類似:

$scope.mod1 = "";
$scope.mod2 = "";
$scope.inputChange = function(data) {
  chrome.storage.local.set({
    $scope.model.id : data,
  }, function() {
    console.log("success!");
  });
}

無法弄清楚如何獲取更改的模型的ID。 還有其他建議來保留有關變更的數據嗎?

編輯

經過多次評論(謝謝),我得到了以下內容( jsbin ):

 var app = angular.module('example', []); app.controller('example', ["$scope", "$log", function($scope, $log) { $scope.form = { form_fields: ["mod1", "mod2", "mod3"], module: { "mod1": null, "mod2": null, "mod3": null, }, error: { "mod1": false, "mod2": false, "mod3": false, }, field_attr: { "mod1": { type: "text", placeh: "Module-1 Input", }, "mod2": { type: "password", placeh: "Module-2 Input", }, "mod3": { type: "text", placeh: "Module-3 Input", }, } }; $scope.inputChange = function(modID) { $log.warn("Module: " + modID + "; value: " + $scope.form.module[modID]); }; } ]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="example" ng-controller="example"> <div id="form-gen" ng-repeat="field in form.form_fields"> <input type="{{form.field_attr[field].type}}" id="{{field}}-in" placeholder="{{form.field_attr[field].placeh}}" ng-model="form.module[field]" ng-model-options="{ debounce: 1000 }" ng-change="inputChange(field)"> </div> </body> 

還有什么可以改進的嗎?

您可以將$event傳遞到您的on-change函數中。 然后,在您的控制器中,您可以執行$ event.target來查找更改的html元素。

<input type="text" ng-model="mod1" ng-change="inputChange($event)" ng-model-options="{ debounce: 250 }">
<input type="text" ng-model="mod2" ng-change="inputChange($event)" ng-model-options="{ debounce: 250 }">


$scope.inputChange = function($event) {
  var changedInput = $event.target;
}

抱歉,這不適用於ng-change ng-change是指令,而不是事件處理程序。 如果您要使用ng-keypress ,它將起作用。

另外,您也可以使用watch

  $scope.$watch('mod1', function(newMod, oldMod){
    if(newMod == oldMod) return;

    console.log('mod1 changed!');
  });

  $scope.$watch('mod2', function(newMod, oldMod){
    if(newMod == oldMod) return;

    console.log('mod2 changed!');
  });

示例: https//jsbin.com/teparofogi/1/edit?html,js,console,output

您可以將其傳遞給on-change函數,並使用以下代碼段獲取更改后的輸入元素:

$scope.inputChange = function(e) {
   var changedInput = e.target; //you can access further prop too       
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM