Javascript 仅获取模型对象上的筛选数据作为结果,angularjs
我的代码是这样的Javascript 仅获取模型对象上的筛选数据作为结果,angularjs,javascript,angularjs,Javascript,Angularjs,我的代码是这样的 <body ng-app="myApp" ng-controller="MainCtrl"> <div>Name only <input ng-model="search.name" /> <br /> <table id="searchObjResults"> <tr>
<body ng-app="myApp" ng-controller="MainCtrl">
<div>Name only
<input ng-model="search.name" />
<br />
<table id="searchObjResults">
<tr>
<th>Name</th>
<th>Phone</th>
</tr>
<tr ng-repeat="friendObj in friends | filter:search:strict | limitTo:1">
<td>{{friendObj.name}}</td>
<td>{{friendObj.phone}}</td>
</tr>
</table>
</div>
<div>
<button type="button" id="btn_submit" ng-click="submitForm()">Get rates</button>
</div>
正如您所看到的,在我的屏幕上,一次只有一个朋友处于活动状态。当我按下提交按钮时,我希望该数据(过滤的单行)是我当前$scope.friends
上的唯一值,以便我可以将其作为所选数据发送到外部服务。有人能指出我需要做什么吗
注意:我无法更改此按钮的位置。为什么不将您的按钮作为表格行的一部分,因为只有一个按钮
然后,按钮的ng click函数处理程序可以简单地获取您感兴趣的实际friendObj参数:
<button type="button" ng-click="submitForm( friendObj )">Get rates</button>
获取费率
编辑:如果你不能移动按钮,实际上有一种方法可以做到这一点;使ng repeat在新阵列上运行,该阵列可在ng repeat外部访问。因此,您的ng repeat语句变为:
<tr ng-repeat="friendObj in newArray = (friends | filter:search:strict | limitTo:1)">
然后,您的按钮可以简单地引用单元素数组:
<button type="button" ng-click="submitForm( newArray )">Get rates</button>
获取费率
:-)如果将筛选器放在控制器中而不是视图中,则可以设置submitForm
函数可以使用的变量,如$scope.result
。例如,在HTML中,可以向搜索字段添加ng change
指令,如下所示:
<input ng-model="search.name" ng-change="updateResult()" />
然后在控制器中:
$scope.search = {name: ''};
$scope.updateResult = function() {
$scope.result = $filter('filter')($scope.friends, $scope.search.name)[0];
}
$scope.updateResult();
// ...
$scope.submitForm = function() {
// $scope.result can be used here
}
编辑:这种方法的优点是它有点枯燥,因为您不需要在提交表单中重新筛选。MarcoS的方法有一个优点,就是要短得多 试试这个:
$scope.submitForm = function () {
var data = $filter('filter')($scope.friends, $scope.search.name);
};
Fiddle.有趣的答案,我曾考虑提到这一点,但它的缺点是每次按键都会调用updateResult()函数。在本例中可能是可以的,但应该注意!我真的不能改变那个按钮的位置。这是毫无疑问的好吧,那么你就必须按照Eric提到的方法做些事情——要么用零钱,要么用手表,每次更新时都要存储所选内容:)你的第二个答案太棒了。谢谢
$scope.search = {name: ''};
$scope.updateResult = function() {
$scope.result = $filter('filter')($scope.friends, $scope.search.name)[0];
}
$scope.updateResult();
// ...
$scope.submitForm = function() {
// $scope.result can be used here
}
$scope.submitForm = function () {
var data = $filter('filter')($scope.friends, $scope.search.name);
};