Javascript 无法从angular app.factory获取值
我试图在控制器之间共享变量,所以我使用angular的工厂。我有以下相同的代码:Javascript 无法从angular app.factory获取值,javascript,angularjs,Javascript,Angularjs,我试图在控制器之间共享变量,所以我使用angular的工厂。我有以下相同的代码: var app = angular.module('chartApp', ['ngRoute']); app.factory('UserVerified', function() { return {bool: false}; }); app.config(function ($routeProvider) { $routeProvider .when('/',{ te
var app = angular.module('chartApp', ['ngRoute']);
app.factory('UserVerified', function() {
return {bool: false};
});
app.config(function ($routeProvider) {
$routeProvider
.when('/',{
templateUrl: 'pages/home.html',
controller: 'PredictionController'
})
});
app.controller('PredictionController', ['$scope', '$http', '$interval', function($scope, $http, $interval){
$scope.hasPermission = UserVerified;
}]);
在HTML上,我只是使用haspmission.bool
来设置
的可见性
但问题是angularjs无法识别“app.factory”中定义的UserVerified
我遇到以下错误:
ReferenceError: UserVerified is not defined
我提到以下几点:
我能找到的唯一区别是,我使用的依赖项在上面链接的示例中没有使用 你需要这样做
app.controller('PredictionController', ['$scope', '$http', '$interval', 'UserVerified', function($scope, $http, $interval, UserVerified){
$scope.hasPermission = UserVerified.bool;
}]);
您需要将服务作为参数传递给控制器您需要在控制器中注入自定义服务
app.controller('PredictionController', ['$scope', '$http', '$interval','UserVerified',function($scope,$http,$interval,UserVerified) {
$scope. hasPermission = UserVerified.bool; //true
}]);
为了避免在代码缩小后破坏应用程序,您还可以在angularjs中使用$inject来注入依赖项
app.controller("PredictionController",PredictionController);
PredictionController.$inject = [$scope','$http','$interval','UserVerified']//dependencies
function PredictionController($scope,http,interval,UserVerified){
$scope. hasPermission = UserVerified.bool; //true
}
注意:缩小后,服务名称将被重命名,并且可能会破坏您的应用程序您需要将UserVerified注入控制器
app.controller('PredictionController', ['$scope', '$http', '$interval', 'UserVerified', function($scope, $http, $interval, UserVerified){
$scope.hasPermission = UserVerifiedvalue.;
}]);
另外,在UserVerified中,您返回的密钥是保留字。它会起作用,但会造成不必要的混乱
app.factory('UserVerified', function() {
return {value: false};
});
是一个演示版。您关于缩小的评论虽然正确,但有误导性。OP的代码也是小型化安全的,根据angular团队的官方文档,数组表示法是推荐的方法。@AbhishekJain,正确:),刚刚展示了其他方法;)