Upon loading my page, the form is populated with values fetched from an http service. At the top of the form sits a custom directive, specifically a select box:
.directive('categorySelectBox', function(){
return {
restrict: "A",
replace: true,
scope: {
// all properties here need to be added to
// the directive in order to be picked up
taxonomies: '='
,chosen: '='
},
templateUrl: "ngapp/js/tpl/select-box.html"
};
})
The template for this directive is as follows:
<select class="form-control"
ng-options="option.label for option in taxonomies track by option.value"
ng-model="chosen"
chosen="chosen"
taxonomies="taxonomies">
<option value="">Please select a category</option>
My controller implementation looks like this:
.controller('DashboardCtrl', ['$scope', 'DbResourceSrv', function($scope, DbResourceSrv){
$scope.$watch('cid', function() {
$scope.formBusy = true;
$scope.c = DbResourceSrv.getDbResource('response.php', 'company', $scope.cid)
.then(function(data) {
$scope.c = data;
angular.forEach(data, function(value, key) {
$scope.c.push({key: value});
});
});
$scope.tax = DbResourceSrv.getDbResource('response.php', 'taxonomy', '')
.then(function(data) {
$scope.taxonomies = [];
$scope.chosen = [];
angular.forEach(data, function(value, key) {
$scope.taxonomies.push({label: value.name, value: value.term_taxonomy_id});
});
var catId = $scope.c.category - 1;
$scope.chosen = $scope.taxonomies[catId];
$scope.formBusy = false;
});
});
$scope.updateCompany = function(cid) {
var formData = $scope.c;
$scope.formBusy = true;
$scope.doCompanyUpdate = DbResourceSrv.updateDbResource('response.php', cid, formData)
.then(function(response) {
$scope.formBusy = false;
});
};
}]);
Typically, I expect to see the category loaded from the database separately via $scope.tax
.
However, my attempts at using $watch
on the chosen scope property have not yielded the desired results. Similarly, employing a directive controller to ensure that scope.chosen
is set there hasn't resolved the issue. It seems that when both processes are initiated with promises, the category fetching fails if one loads before the other due to their tight coupling.
Do you have any suggestions for code enhancements to prevent the default Please select a category
option from being automatically selected upon page load?