When building a web app where every page depends on many data sources, what\'s the best way to fetch the initial bits of data? When I look at twitter, I see the tweets that are
One way to do it is to create a directive that handles the initialization before binding happens. For example:
app.directive('initdata', function() {
return {
restrict: 'A',
link: function($scope, element, attrs) {
if ( attrs.ngBind !== undefined)
{
$scope[attrs.ngBind] = attrs.initdata ? attrs.initdata : element.text();
}
}
};
});
This directive takes either the attribute value as initial value for the bound $scope property, or the textvalue of the element.
Example usage:
Lorem Ipsem
Working example on http://jsfiddle.net/6PNG8/
There's numerous way to elaborate on this; for example parsing the initdata as json and merging it with the scope, and making it work for more complicated binds, like $root.someprop
. But the basis is remarkably simple.