我有一张这样的表:
+--------+----------+---------+
| ID | Nombre | PadreID |
+--------+----------+---------+
| 1 | KENWORTH | 0 |
| 2 | VOLVO | 0 |
| 3 | T6000 | 2 |
| 4 | T800 | 1 |
+--------+----------+---------+
这样的选择:
<select class="form-control" ng-hide="Catalogos.length==0" ng-change="filtro(selected)"
ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>
我使用以下功能充电:
function cargarCatalogo() {
apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/",
null,
function(res) {
$scope.Catalogos = res.data;
$scope.selected = $filter('filter')($scope.Catalogos, {
ID: $scope.padreID
}, true);
$scope.filtro($scope.selected);
},
errorCatalogo);
}
我希望选择我的数据库,例如,如果我点击编辑到T6000
它有PadreId = 2
,那么我选择的VOLVO
应该是ID = 2
但是如果我选择PadreId = 1
的T800编辑应该是具有ID = 1
如何正确使用filter
,然后选择选择该选项?
当我控制它时,我得到正确的值:
但我无法使用$scope.filtro($scope.selected);
获取默认值,有人可以帮助我吗?
更新
$ scope.filtro定义:
$scope.filtro = function(selected) {
$scope.selectedID = selected.ID;
}
更新2
作为Vanojx1评论我使用这样的find函数:
function cargarCatalogo() {
apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/",
null,
function(res) {
$scope.Catalogos = res.data;
},
errorCatalogo);
}
$scope.filtro = function(selected) {
$scope.selectedID = selected.ID;
}
$scope.selected = $scope.Catalogos.find(function(catalog) {
return catalog.ID == $scope.padreID;
});
$scope.filtro($scope.selected);
但我得到selected is undefined
,有人可以帮我吗?
答案 0 :(得分:1)
$filter
函数返回一个数组,在$scope.selected
中你需要一个对象,find函数就足够了:
var myapp = angular.module('myapp', []);
myapp.controller('appCtrl', function($scope) {
$scope.Catalogos = [{ID: 1,Nombre: "KENWORTH",PadreID: 0},{ID: 2,Nombre: "VOLVO",PadreID: 0},{ID: 3,Nombre: "T6000",PadreID: 2},{ID: 4,Nombre: "T800",PadreID: 1}];
$scope.padreID = 2;
$scope.filtro = function(selected) {
$scope.selectedID = selected.ID;
}
$scope.selected = $scope.Catalogos.find(function(catalog) {
return catalog.ID == $scope.padreID
});
$scope.filtro($scope.selected);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="appCtrl">
<select class="form-control" ng-hide="Catalogos.length==0" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>
</div>
&#13;