【问题标题】:Async data from controller to directive: unknown provider error从控制器到指令的异步数据:未知的提供者错误
【发布时间】:2015-04-07 16:19:10
【问题描述】:

我想实现一个具有隔离作用域的指令和一个双向绑定到异步加载数据的控制器作用域的指令。

部分html:

<body ng-app = 'authorGraph' ng-controller = 'GraphCtrl'>
<graph-dir/>

Javascript:

var authorGraph = angular.module('authorGraph', []);

authorGraph.directive('graphDir', function () {
return {
    scope: {
     graphData: '=' //two way binding 
    },
    restrict: 'E',
    link: function (scope, element) {
        //do something with D3.js to visualise the data here
    }
};

浏览互联网,我发现 Promise 可以解决问题(此代码位于指令实现之前)

authorGraph.config(function($routeProvider) {
$routeProvider.when('/',
    {
        controller: 'GraphCtrl',
        resolve: {
            getData: function ($http) {
                return $http.get('graph_data.json').then(function (data) {
                    return data;
                });
            }
        }
    });
});

authorGraph.controller('GraphCtrl', function GraphCtrl($scope, getData) {
    $scope.graphData = getData;
});

但是,我被错误困住了

未知提供者:getDataProvider

【问题讨论】:

    标签: angularjs asynchronous angularjs-directive angularjs-scope


    【解决方案1】:
    authorGraph.controller('GraphCtrl', function GraphCtrl($scope, getData) {
        $scope.graphData = getData;
    });
    

    在上面的代码中,当你注入一些东西作为依赖时,它会开始寻找合适的提供者。在您的情况下,它正在寻找 getDataProvider 并且找不到任何服务。

    当您使用解析时,返回的解析参数将在您的$scope 对象中可用。您无需将其作为依赖项注入。

    上面的代码应该是:

    authorGraph.controller('GraphCtrl', function GraphCtrl($scope) {
        $scope.graphData = $scope.getData;
    });
    

    【讨论】:

      猜你喜欢
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 2013-02-21
      相关资源
      最近更新 更多