initial data loading in angularjs

前端 未结 4 1345
借酒劲吻你
借酒劲吻你 2021-02-05 04:19

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

4条回答
  •  迷失自我
    2021-02-05 04:56

    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.

提交回复
热议问题