2015-06-23 137 views
1

我想在控制器之間共享變量,所以我正在使用角度的工廠。我有下面的代碼是一樣的:無法從角度app.factory獲取價值

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我只是用hasPermission.bool設置<div>的知名度。

但問題是angularjs無法識別「app.factory」中定義的UserVerified。

我收到以下錯誤:

ReferenceError: UserVerified is not defined 

我提到以下幾點:Share data between AngularJS controllers

唯一的區別我能找到的是,我使用的是未在例如在上面的鏈接中使用的依賴。

回答

1

你需要在你的控制器

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 
    } 

注:服務名稱將縮小後重命名,並且打破您的應用程序

+0

您對minification的評論雖然正確,但具有誤導性。 OP的代碼也是小型化的,並且根據角度團隊的官方文檔,陣列符號是推薦的方法。 –

+0

@AbhishekJain,正確:),只是顯示了其他方法;) –

1

你需要這樣做,

app.controller('PredictionController', ['$scope', '$http', '$interval', 'UserVerified', function($scope, $http, $interval, UserVerified){ 

    $scope.hasPermission = UserVerified.bool; 

}]); 

您需要將服務作爲參數傳遞給控制器​​

0

你需要注入UserVerified到控制器中沉醉。

app.controller('PredictionController', ['$scope', '$http', '$interval', 'UserVerified', function($scope, $http, $interval, UserVerified){ 

    $scope.hasPermission = UserVerifiedvalue.; 

}]); 

另外,在UserVerified中,您返回的是一個保留字的關鍵字。它會工作,但會造成不必要的混淆。

app.factory('UserVerified', function() { 
    return {value: false}; 
}); 

Here是作爲演示的蹲跳者。