我正在尝试将两个输入框的值传递给单个 Controller 函数。
<div class="container" ng-controller="MainCtrl">
<div class="row">
<div class="col-lg-6">
<input type="text" name="regex" class="form-control" placeholder="Regex"
ng-model="do_parsing.data"
ng-model-options="{ getterSetter: true }">
</div>
<div class="col-lg-2">
<input type="text" name="modifier" class="form-control" placeholder="modifier">
</div>
</div>
<hr>
<div class="form-group">
<textarea class="form-control" id="input_data" rows="10" style="width: 555px; height: 214px"
placeholder="Insert your test string here"
ng-model="do_parsing.data"
ng-model-options="{ getterSetter: true }"></textarea>
</div>
<div class="form-group">
<pre> <span ng-bind="do_parsing.data()"></span></pre>
</div>
</div>
这是我的 controller.js
文件,
app.controller('MainCtrl', function ($scope) {
var _data = '';
$scope.do_parsing = {
data: function(newData) {
if (newData != undefined) {
alert(newData);
}
return arguments.length ? (_data = newData) : _data;
}
};
});
我想将第一个输入框和文本区域的值传递给 do_parsing
函数,并且我希望该函数将解析后的数据返回到 pre
标记。也就是说,只要第一个输入框的值和 text-area
发生变化,这个 do_parsing
函数就应该执行。我已经尝试过上面的方法,但它在所有三个地方反射(reflect)了相同的值。
最佳答案
您可以将输入字段和文本区域绑定(bind)到 $scope 对象上的某些字段:
<input type="text"
name="regex"
class="form-control" placeholder="Regex"
ng-model="inputValue"
ng-model-options="{ getterSetter: true }" />
和文本区域:
<textarea class="form-control"
id="input_data"
rows="10"
style="width: 555px; height: 214px"
placeholder="Insert your test string here"
ng-model="textareaValue"
ng-model-options="{ getterSetter: true }">
</textarea>
以及生成的跨度到将被调用的函数:
<pre>
<span ng-bind="do_parsing.data()"></span>
</pre>
现在您可以在 Controller 上定义此函数:
app.controller('MainCtrl', function ($scope) {
$scope.inputValue = '';
$scope.textareaValue = '';
$scope.do_parsing = {
data: function() {
// calculate some expression using the 2 values
// which will be shown in the resulting span
return $scope.inputValue + ' | ' + $scope.textareaValue;
}
};
});
这是一个 live demo
.
关于javascript - 如何将多个输入框值传递给 Controller 中定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34574508/