0

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...

11
  • use $rootScope Commented Jan 22, 2018 at 15:44
  • do you mind providing me an example? not too familiar with how to use $rootScope Commented Jan 22, 2018 at 15:47
  • 1
    same code what you are using, inject $rootScope and check. Commented Jan 22, 2018 at 15:47
  • 7
    @Bharadwaj that is just promoting a bad practice that shouldn't be used Commented Jan 22, 2018 at 15:56
  • 1
    @Bharadwaj no it is not and using it as a data store is a well recognized poor practice Commented Jan 22, 2018 at 16:00

1 Answer 1

2

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);        
      }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.