确定哪个输入字段触发ng-change?

时间:2015-12-02 16:42:15

标签: javascript angularjs chromium

我有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):

&#13;
&#13;
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]);
    };

  }
]);
&#13;
<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>
&#13;
&#13;
&#13;

还有什么东西可以改进吗?

2 个答案:

答案 0 :(得分:1)

您可以将<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; } 传递给您的更改功能。 然后在您的控制器中,您可以执行$ event.target来查找更改的html元素。

ng-change

抱歉,这不适用于ng-changeng-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!'); });

{{1}}

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

答案 1 :(得分:-1)

您可以将此传递给on-change函数,并使用以下代码段获取更改的输入元素:

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