1

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.

Community
  • 1
  • 1
mribot
  • 519
  • 1
  • 11
  • 29

3 Answers3

1

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

Sudhansu Choudhary
  • 3,322
  • 3
  • 19
  • 30
1

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

Shushanth Pallegar
  • 2,832
  • 1
  • 14
  • 16
0

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.

Abhishek Jain
  • 2,957
  • 23
  • 35