[英]About AngularJS $RouteParams
I just started to learn AngularJS.我刚开始学习 AngularJS。 When I use the
.service
of AngularJS, if I inject $RouteParams
, but I don't actually use $RouteParams
, then the .service
doesn't work.当我使用 AngularJS 的
.service
时,如果我注入$RouteParams
,但我实际上并没有使用$RouteParams
,那么.service
就不起作用。
myApp.service('myService', function() {
this.name = 'myServiceName';
var self = this;
this.nameLength = function () {
return self.name.length;
};
});
myApp.controller('mainController', ['$scope','$log','$routeParams','myService',function($scope, $log,myService,$routeParams) {
$scope.handle = myService.name;
}]);
What's weird is that if I do use $RouteParams
in the controller, then it works, why would the $RouteParams
influence the use of .service
?什么奇怪的是,如果我使用
$RouteParams
在控制器中,然后它的作品,为什么会在$RouteParams
影响使用的.service
?
The problem is not with $routeParams
but the order of dependencies injected.问题不在于
$routeParams
而在于注入的依赖项的顺序。 Interchange the order of dependencies to be same as the annotated dependencies.将依赖项的顺序交换为与注释的依赖项相同。 In your code you have annotated the
$routeParams
service before myService
: ['$scope','$log','$routeParams','myService'
but while using them in injected depndencies as callback function parameters you are using $routeParams
after myService
.在您的代码中,您在
myService
之前注释了$routeParams
服务: ['$scope','$log','$routeParams','myService'
但是在注入的依赖项中使用它们作为回调函数参数时,您在myService
之后使用$routeParams
. When you try to use the myService.name
, it actually refers to $routeParams
which does not have a property named name
.当您尝试使用
myService.name
,它实际上是指没有名为name
的属性的$routeParams
。 Change your code as below and it will work如下更改您的代码,它将起作用
myApp.service('myService',function(){
this.name='myServiceName';
var self=this;
this.nameLength=function(){
return self.name.length;
};
});
myApp.controller('mainController', ['$scope','$log','$routeParams','myService',function($scope, $log,$routeParams, myService) {
$scope.handle = myService.name;
}]);
Create your controllers like this.像这样创建你的控制器。 This way is less confusing and more readable.
这种方式不那么混乱且更具可读性。
myApp.controller('mainController', function($scope, $log,myService,$routeParams) {
$scope.handle = myService.name;
});
Aditya Singh already explained this pretty well. Aditya Singh 已经很好地解释了这一点。 To prevent this mistake, you could change code style to the following:
为防止出现此错误,您可以将代码样式更改为以下内容:
myApp.controller('mainController',
['$scope', '$log', '$routeParams', 'myService',
function($scope, $log, $routeParams, myService) {
$scope.handle = myService.name;
}]);
This also prevents you from vertical scrolling when there are many injections in your controller.这也可以防止您在控制器中有许多注入时垂直滚动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.