在 AngularJS 中在控制器和工厂之间共享 $scope
sharing $scope between controller and factory in AngularJS
我有一个变量 'file' 被传递给我在同一个控制器中使用的指令。现在我想在我正在创建的工厂中使用相同的 '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...
此处可以使用$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);
}
我有一个变量 'file' 被传递给我在同一个控制器中使用的指令。现在我想在我正在创建的工厂中使用相同的 '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...
此处可以使用$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);
}