在 AngularJS 中的控制器和工厂之间共享$scope



我有一个变量"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);        
      }

文件类别.工厂.js

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

我希望能够在我的工厂中使用 $scope.file,就像这样......

在这里可以使用$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);        
      }

最新更新