I have what should be a very simple task. I want to sort a drop down menu in angular based off of a given parameter. Should be easy.
I make a call to a dataservice the returns some data like so:
"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"
}]}
My task is to make a list with all the DefCom values that also have an associated MUST value. I need to list "DefCom" numbers that have a "Req" that is "MUST", inside of a dropdown. So in my example, my dropdown would have values 111 and 333.
In my controller, I execute the call
$scope.getDefCom = function(){
MyAPIservice.getDefCom().success(function(response){
$scope.info = response.data.this_info;
$scope.infoList = $scope.info;
});
}
Where I have this factory:
angular.module('MyAPI.services', [])
.factory('MyAPIservice', function($http) {
var MyAPI = {};
MyAPI.getDefCom = function () {
return $http({
method: 'GET',
url: '/thisis/mylink/'
});
};
return invoiceheaderAPI;
});
This works for my first initiative, make a drop down that will list DefCom numbers. However, next I need to filter them.
$scope.require = MUST in this example.
Inside my template:
<option ng-repeat="option in DefComList" value="{{option.DefCom}}">{{option.DefCom}} </option>
I tried doing a filter like so:
ng-repeat="option in DefComList | filter: {Req: $scope.require}"
However upon more reading I couldn't find anything where you can insert a $scope variable into a filter. Most of the suggestions leaned towards writing your own filter. I did this, using angular.forEach. My filter is below:
$scope.filterDefs = function($scope) {
var clrreturn = false;
angular.forEach($scope.info, function(value, key) {
if (value.DefCom == $scope.require)
clrreturn = true;
});
return clrreturn;
};
However, my custom filter is running before getting the results of $scope.info from the $scope.getDefCom function. This is throwing an Error: undefined is not an object (evaluating '$scope.info') before $scope.info is ready. I know that this has to do with promises, so I tried writing in deferred promises. However, this didn't work either, and I have gotten frustrated because this seems like it should be a very simple task and I might be making it way harder for myself than it should be.