mribot
mribot

Reputation: 529

Unable to fetch value from angular app.factory

I am trying to share variable among the controller so I am using angular's Factory. I have following code for the same:

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;

}]);

and on HTML i am just using hasPermission.bool to set visibility of a <div>.

But the issue is angularjs is unable to identify UserVerified defined in "app.factory".

I am getting following error:

ReferenceError: UserVerified is not defined

I referred following : Share data between AngularJS controllers

Only difference I can find is, I am using dependencies which is not used in the example in the above link.

Upvotes: 1

Views: 67

Answers (3)

Shushanth Pallegar
Shushanth Pallegar

Reputation: 2862

you need to inject your custom service in your controller

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

     $scope. hasPermission = UserVerified.bool; //true

  }]);

inorder to avoid breaking of your application after minification of code you can also use $inject in angularjs to inject dependecies.

 app.controller("PredictionController",PredictionController);

 PredictionController.$inject = [$scope','$http','$interval','UserVerified']//dependencies



 function PredictionController($scope,http,interval,UserVerified){
   $scope. hasPermission = UserVerified.bool; //true
  }

Note: Services names will be renamed after the minification and can indulge in breaking your application

Upvotes: 1

Abhishek Jain
Abhishek Jain

Reputation: 2977

You need to inject UserVerified into your controller.

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

    $scope.hasPermission = UserVerifiedvalue.;

}]);

Plus, in UserVerified you are returning a key which is a reserved word. It will work but will create unnecessary confusion.

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

Here is a plunker as a demo.

Upvotes: 0

Sudhansu Choudhary
Sudhansu Choudhary

Reputation: 3360

You need to do this,

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

    $scope.hasPermission = UserVerified.bool;

}]);

You need to pass the service as a parameter to controller

Upvotes: 1

Related Questions