javascriptangularjsangularjs-scopeangularjs-factory

sharing $scope between controller and factory in AngularJS


I have a variable 'file' that is being passed to a directive which i am using in the same controller. Now i want to use that same 'file' in the factory that i am creating but i'm not sure if there is an easy way to share that same variable between controller and factory.

for example...

fileCategory.directive.js:

.directive('fileCategory', function () {
      return {
        templateUrl: '...'
        restrict: 'EA',
        replace: true,
        scope: {
          file: '='
        },
        controller: 'fileCategoryController'
      };
    });

fileCategory.controller.js:

.controller('fileCategoryController', function($scope) {

      if(!$scope.file) {
        return;
      } else {
        console.log($scope.file);        
      }

fileCategory.factory.js

.factory('fileCategoryList', function () {

  categories.get = function() {
    if($scope.file){
      return this.categories;
    } else{
      return;
    }
  };

I want to be able to use $scope.file in my factory like so...


Solution

  • Using $rootScope is possible here, but please don't use it in this case. Better practice is use service for storing data, and manipulate between different components. When your application will grow, it can be problem store more data in global $rootScope.

    .service('CategoryService', function () {
     this.file = ...
      }
    

    then implement service to controller, factory or anywhere you need

    .controller('fileCategoryController', function($scope, CategoryService ) {
          $scope.file = CategoryService.file
    
          if(!CategoryService.file) {
            return;
          } else {
            console.log($scope.file);        
          }