Having encountered similar challenges to this specific scenario, I am currently facing issues with handling asynchronous data within my directives. The main issue arises when trying to pass asynchronously fetched data into these directives. Initially, I attempted to achieve this by utilizing the scope property on the directive in the following manner:
scope: {
myAsyncData: '='
}
To address potential timing discrepancies, I incorporated a $watch
function within the link function to update the model based on changes in the scoped value. However, this led to javascript errors as the asynchronous data had not been retrieved yet, prompting me to seek advice from the aforementioned question. Subsequently, I modified the $watch
implementation as follows:
scope.$watch(scope.foo, function() {
if (angular.isDefined(scope.myAsyncData))
{
//logic based on myAsyncData
}
}
While this adjustment prevented javascript errors, it failed to trigger the $watch
again upon data retrieval, resulting in an inaccurate view of the model. Experimenting with assigning $scope.foo
within a $timeout
proved unreliable and excessively dependent on timing.
My inquiry revolves around determining the most appropriate method for handling asynchronous data within directives. Some examples suggest accessing data within the directive using:
scope.$eval(attrs.myAsyncData);
However, implementing this approach did not yield any noticeable differences compared to the initial myAsyncData: '='
strategy. Considering alternative solutions such as retrieving data through services or directly within the directive itself raises concerns regarding the delegation of responsibilities. Ideally, I aim for the directive solely focusing on displaying and updating user-interacted data rather than sourcing it.
If there are fundamental principles or best practices that I may have overlooked in addressing this matter appropriately, I welcome any insights or guidance offered.