在AngularJS中共享控制器和工厂之间的范围

时间:2018-01-22 15:42:30

标签: javascript angularjs angularjs-scope angularjs-factory

我有一个变量'file',它被传递给我在同一个控制器中使用的指令。现在我想在我正在创建的工厂中使用相同的“文件”,但我不确定是否有一种简单的方法可以在控制器和工厂之间共享相同的变量。

例如......

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;
    }
  };

我希望能够在我的工厂中使用$ scope.file ...

1 个答案:

答案 0 :(得分:2)

这里可以使用$ rootScope,但在这种情况下请不要使用它。更好的做法是使用服务来存储数据,并在不同的组件之间进行操作。当您的应用程序增长时,可能会在全局$ rootScope中存储更多数据。

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

然后将服务实施到控制器,工厂或任何您需要的地方

.controller('fileCategoryController', function($scope, CategoryService ) {
      $scope.file = CategoryService.file

      if(!CategoryService.file) {
        return;
      } else {
        console.log($scope.file);        
      }
相关问题