我想实现一个指令,该指令具有一个独立的作用域和到异步加载数据的控制器作用域的双向绑定。
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<-getData
authorGraph.controller('GraphCtrl', function GraphCtrl($scope, getData) {
$scope.graphData = getData;
});
在上面的代码中,当您注入一些东西作为依赖项时,它将开始寻找合适的提供程序。在您的案例中,它正在寻找getDataProvider,但它不能;找不到任何服务。
使用解析时,返回的解析参数将在$scope
对象中可用。您不需要将其作为依赖项注入。
以上代码应为:
authorGraph.controller('GraphCtrl', function GraphCtrl($scope) {
$scope.graphData = $scope.getData;
});