One issue I frequently encounter in my controllers is a repetitive piece of code:
// Get first product from list
Product.get_details( id )
.success(function ( data ) {
// Setup product details
$scope.active_product = data;
});
To avoid this redundancy, I aim to move it into a factory for better code organization.
The challenge arises when I want to access $scope.active_product
while ensuring it is watched by the digest loop.
Within the Product factory:
// ajax function that fetches product data
var get_details = function( id ){ ... }
var set_active_product = function( active_product, id ){
// Get first product from list
get_details( id )
.success(function ( data ) {
// Setup product details
active_product = data;
});
};
Meanwhile, in my controller:
Product.set_active_product( $scope.active_product, id );
Although this method works, the issue lies in $scope
not being monitored by the $digest
loop.
Is there an alternative approach to achieve this without passing a $scope
-scoped variable?