您好,我创建了一个名为 billerModel 的模型和一个具有 billers 变量的解析路径。现在我想在我的 Controller 中检索并分配这个变量,但我得到了这个 billerData unknown provider 错误。以下是我的路线代码:
app.config(["$routeProvider", "$httpProvider",'$locationProvider',function($routeProvider, $httpProvider, $locationProvider) {
$routeProvider
.when("/billers", {
templateUrl: 'admin/billers/index.html',
controller: 'billerController',
resolve: {
billerData: function(billerModel) {
return billerModel.getData();
}
}
});
下面是我的模型代码
app.factory('billerModel', ['$http', '$cookies', function($http, $cookies) {
return {
getData: function() {
return $http({
method: 'GET',
url: 'billers'
});
}
}
}]);
下面是给我错误的 Controller 代码
app.controller('billerController', ['$scope', 'billerData',
function($scope, billerData){
$scope.billers = billerData;
}]);
我也尝试从我的 View 中删除 ng-controller,但如果我这样做,我会收到未知变量的错误
<div style="text-align: left;" ng-controller="billerController">
{{ billers }}
</div>
下面是一个 jsfiddle,但我不熟悉如何使用它,但这里包含了基本结构 https://jsfiddle.net/bd06cctd/1/
最佳答案
解析 .when
中的数据 block 只能注入(inject)由 .when
定义的 Controller 中堵塞。由 ng-controller
注入(inject)的子 Controller 指令不能注入(inject)解析数据。
另外,如果你注入(inject) billerController
在.when
使用 ng-controller
阻止和 .when
中的指令 block 模板,那么 Controller 将被实例化两次。
$routeProvider
还使解析数据在 $resolve
的 View 范围内可用属性(property)。 ng-controller
实例化的子 Controller 指令可以使用它。
app.controller('childController', ['$scope',
function($scope){
$scope.billers = $scope.$resolve.billerData;
}]);
由 ng-controller
实例化的 Controller 指令将找到 $resolve
从 View 范围通过原型(prototype)继承的属性。
来自文档:
- resolve -
{Object.<string, Function>=}
- An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and$routeChangeSuccess
event is fired. If any of the promises are rejected the$routeChangeError
event is fired. For easier access to the resolved dependencies from the template, the resolve map will be available on the scope of the route, under$resolve
(by default) or a custom name specified by theresolveAs
property.
关于angularjs - 获取解析变量并传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39504840/