获取初始数据angularjs/Dilesive的适当策略



我有一个应用程序,加载默认页面,该默认页面需要一些数据才能自行渲染。

在页面中,我有一个指令,可以将数据包装在一些视图元素中。我希望应用程序在指令"加载"时获取数据,以便一旦返回数据,指令就可以启动显示数据的过程(例如,某些列表的NG-重复等等。)。

。 。

启动REST服务以获取数据的最佳生命周期阶段是什么(编译,链接,后链接)?

请注意,其余服务在Angular Service对象中声明并注入控制器。

示例:

<div ng-controller="MainCtrl">
  <div my-directive data="{{data}}>
</div>
angular.module('angularTestApp')
    .directive('myDirective', function () {
        return {
            templateUrl: 'route/to/my/view/template.html',
            restrict: 'AE',
            compile: function(tElement, tAttrs, transclude) {
                //fetch data here?
                scope.getMyData();  //calls REST service and sets value in the controller and set value for binding
            }
            link: function postLink(scope, element, attrs) {
                scope.doSomething = function () {
                    console.log('I'm doing something useful');
                }
                //does call to controller to fetch data go here?
                scope.getMyData();  //calls REST service and set value in the controller for binding
            }
        };
    });

控制器:

angular.module('angularTestApp')
    .controller('MainCtrl', ['$scope', 'InjectedService', function ($scope, InjectedService) {
    $scope.data = {};  
    $scope.getData = function() {
       InectedService.get(function(data) {
       $scope.data = data;

我更喜欢在指令本身上使用孤立的示波器,并在MainCtrl控制器内使用解决方案。

如果您最终会出现 $scope.data是什么...只是在 MainCtrl中做 $scope.data = InjectedService.get();,它应该起作用。

只要注射服务返回$ Q Promise,它将全部自动。您不需要您编写的大多数代码。

换句话说,让您的控制器获取数据。您的指示不必担心。

最新更新