Looking to accomplish a straightforward task here. I need to organize a dropdown menu in angular based on a specified parameter. Sounds simple, right?
Here's the data returned from a call to the dataservice:
"success" : true,
"data" : {
"this_status" : [{
"DefNo" : "111*A",
"Com" : "111",
}, {
"DefNo" : "222*B",
"Com" : "222",
}, {
"DefNo" : "333*C",
"Com" : "333",
}
];
"this_info" : [{
"Req" : "MUST",
"DefCom" : "111",
}, {
"Req" : "NoMUST",
"DefCom" : "222"
}, {
"Req" : "MUST",
"DefCom" : "333"
}]}
The goal is to generate a list of "DefCom" values that also have a corresponding "MUST" value. I want to display "DefCom" numbers with a "Req" set as "MUST" in a dropdown menu. In this case, the dropdown should include 111 and 333.
In the controller, I trigger the function:
$scope.getDefCom = function(){
MyAPIservice.getDefCom().success(function(response){
$scope.info = response.data.this_info;
$scope.infoList = $scope.info;
});
}
This factory is used for the purpose:
angular.module('MyAPI.services', [])
.factory('MyAPIservice', function($http) {
var MyAPI = {};
MyAPI.getDefCom = function () {
return $http({
method: 'GET',
url: '/thisis/mylink/'
});
};
return invoiceheaderAPI;
});
So far, this successfully lists the DefCom numbers in the dropdown. Now, the next step is to apply a filter.
In this example, $scope.require = MUST
.
Within the template:
<option ng-repeat="option in DefComList" value="{{option.DefCom}}">{{option.DefCom}} </option>
Attempting to add a filter like this:
ng-repeat="option in DefComList | filter: {Req: $scope.require}"
Realized inserting a $scope variable into a filter might not work as intended after further research. Most advice suggests creating a custom filter instead. So, I wrote my own using angular.forEach. Here's the filter code:
$scope.filterDefs = function($scope) {
var clrreturn = false;
angular.forEach($scope.info, function(value, key) {
if (value.DefCom == $scope.require)
clrreturn = true;
});
return clrreturn;
};
However, the custom filter runs before receiving the results of $scope.info from the $scope.getDefCom function. This triggers an
Error: undefined is not an object (evaluating '$scope.info')
error before $scope.info is fully loaded. Seems like a promises issue, so I attempted implementing deferred promises without success. Simple task turned challenging, but I refuse to give up!