我想从我的 Controller 访问一个变量,以便我可以在我的服务中使用它!我认为如果我将变量设置为全局变量,我可以在我的服务中访问它,但它不起作用,呵呵。顺便说一句,变量是商店!
这是我创建变量的位置:
$scope.$on('$ionicView.enter', function (e) {
ecommercer.getData().then(function (s) {
$scope.shops = s.vendors
$scope.categories = s.categories
$ionicScrollDelegate.resize()
if ($stateParams.id && $stateParams.id.length > 1) {
$ionicTabsDelegate.showBar(false)
ecommercer.saveShopById($stateParams.id)
$state.go('tab.ecommerce.shop')
}
})
})
这里(同一个文件)是我使用变量的地方:
$scope.$watch('selectedCategory.name', function (newval, oldval) {
if ($scope.selectedCategory.name != undefined) {
$scope.shops = ecommercer.filterByCategory(newval.id)
} else {
$scope.shops = ecommercer.filterByCategory(null)
}
})
这是我在服务文件中创建相同变量的位置:
app.service('ecommercer', function (eapi, $q, storage, $http, endpointHandler, $state, $rootScope, $filter) {
var products, categories, vendors, shops
最后,这是我尝试在我的服务中使用它时的情况:
function filterByCategory(categoryid, shops) {
if (!categoryid) return shops
console.log(shops);
var newlist = []
for (var s in shops) {
if (shops[s].category.split(',').length > 0) {
for (var c in shops[s].category.split(',')) {
if (shops[s].category.split(',')[c] == categoryid) {
newlist.push(shops[s])
}
}
}
}
return newlist
}
最佳答案
您的 Controller 实际上只是 View 和单例服务之间的粘合剂...它们在您的应用程序生命周期中(重新)创建和销毁 - 服务创建一次(单例 - 并在创建后注入(inject)时重用)。
因此,您应该改变您的方法,而不是在 Controller 内的应用程序( Controller /服务)中保存您想要共享的变量 - 在 $scope
对象上 - 您应该在内部创建它您的单例服务ecommercer
。
通过 getter/setter 原理,您可以更新/检索单例服务 ecommercer
内的变量 shops
。
请参阅以下粗略示例来说明您应该如何改变您的方法。
Controller 和服务
angular
.module('app', [])
.controller('MainController', MainController)
.service('ecommercer', ecommercer)
function ecommercer() {
var shops;
return {
setShops: setShops,
getShops: getShops
}
function setShops(shops) {
this.shops = shops;
}
function getShops(shops) {
return this.shops;
}
}
function MainController(ecommercer) {
var vm = this;
this.setShops = setShops;
function setShops() {
ecommercer.setShops([{
id: 1,
name: 'test shop 1'
}, {
id: 2,
name: 'test shop 2'
}]);
vm.shops = ecommercer.getShops();
}
}
查看
<div ng-app="app" ng-controller="MainController as vm">
<div ng-click="vm.setShops()">
Set shops
</div>
<div>
{{vm.shops}}
</div>
</div>
关于javascript - 从 Controller 访问变量到服务 | Angular 1.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44523681/