![](/img/trans.png)
[英]update controller variable and use it in view from directive (angular 1.5)
[英]Accessing variable from controller to service | Angular 1.5
我想從控制器訪問變量,以便可以在服務中使用它! 我以為如果將變量設置為全局變量,則可以在我的服務中訪問它,但是它不起作用。 該變量是商店順便說一句!
這是我創建變量的地方:
$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
}
您的控制器實際上只是您的視圖和單例服務之間的粘合劑……它們在整個應用程序生命周期中被(重新)創建和銷毀-服務僅創建一次(子集-注入后在創建后重用)。
因此,您應該扭轉局面,而不是希望在控制器內部的應用程序(控制器/服務)中共享變量(在$scope
對象上),而應該在單例服務ecommercer
內部創建變量。
通過getter / setter原理,您可以更新/檢索單例服務ecommercer
內部的變量shops
。
請參見以下粗略示例,以說明如何更改方法。
控制器與服務
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.