I have an html page that shows a table with a number of product rows. Each row has a select drop down that allows a user to select a "sheet". Above that table is an info box that shows the selected sheet for all products - that info varies based on what is selected. I have that set as a directive.
My product data (actually it's one item with a product array) is loaded using resolve/resource so comes in as a promise. I am having difficulties setting data such as the master sheet on load because it requires me to look through all the products and these are not available until the view has rendered/promise fulfilled. The directive below illustrates my issue:
app.directive('sheet', function() {
return {
restrict: "EAC",
link: function(scope, elm, attrs) {
// Watch the table data where a user can assign a sheet to a product row
scope.$watch('item.products', function(n, o) {
if (n) {
// Update info on master sheet
setMaster();
}
}, true);
// Master sheet function - it checks if all product sheets are same - if they are then it shows the sheet code
// else it shows "mixed" - or if new then "Select a sheet" - this info is shown above product table page
var setMaster = function() {
var sheets = [];
// If I don't do this then the last setMaster() call (used to init the master sheet in load)
// will throw errors about item.products being undefined
scope.item.$promise.then(function(item) {
item.products.forEach(function(product) {
if (!~sheets.indexOf(product) && product.sheet) sheets.push(product.sheet);
});
});
// Assign info to master sheet variable
scope.master = sheets.length ? sheets.length > 1 ? 'Mixed' : sheets[0].code : 'Select a sheet';
};
// Set on page load
setMaster();
}
};
});
My question is: what is the best way to handle this and other on load (on page (re)load) functions that need the promise resolved. In the directive above I am resolving the promise on each watch event - is this expensive? what is the cleanest way. I have thought about just resolving once in my controller as well but the entire thing seems contrived and I am wondering if there is just some flag or other that I can set to just deal with these issues.
Route:
resolve: {
items: function(Orders, $route) {
return Orders.list(); // Just a simple Resource
}
}
Controller:
app.controller('ViewOrderCtrl', function(scope, item) {
$scope.item = item;
});
Resource:
app.factory('Orders', ['$resource',
function($resource) {
return $resource('/api/orders/:id', {}, {
list: {
method: 'GET',
isArray: true,
transformResponse: function(response, headers) {
var data = angular.fromJson(response);
return data;
}
}
})
}]);
Edit: Tried to resolve in controller but evidently directives get acted upon before so the promise has to be resolved in the directive.