我正在尝试使用工厂服务在我的ionic / angular + phonegap应用程序项目中使用全局变量。
然而,添加一个简单的工厂服务,如下面的那个会以某种方式混淆应用程序&应用程序的所有屏幕都变成纯白色。
.factory('serviceName', function() {
return {}
})
我有两个名为app.js
&的js文件controller.js
app.js看起来像这样有更多的状态:
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers'])
//TRIED ADDING FACTORY HERE
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
});
$urlRouterProvider.otherwise('/app/playlists');
});
我的controller.js
有点看起来像这样有更多的变量&amp;功能:
angular.module('starter.controllers', [])
//ALSO TRIED ADDING FACTORY HERE
.controller('AppCtrl', function($scope, $ionicModal, $timeout,$http) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
// Form data for the login modal
$scope.loginData = {};
})
.controller('PlaylistsCtrl', function($scope) {
$scope.playlists = [
{ title: 'Reggae', id: 1 },
{ title: 'Chill', id: 2 },
{ title: 'Dubstep', id: 3 },
{ title: 'Indie', id: 4 },
{ title: 'Rap', id: 5 },
{ title: 'Cowbell', id: 6 }
];
})
.controller('PlaylistCtrl', function($scope, $stateParams) {
})
我提到这个http://mcgivery.com/ionic-using-factories-and-web-services-for-dynamic-data/开始使用工厂。
我知道可以使用$ rootScope,但它有problems of global variables,所以请帮我使用工厂。另外,如果有人可以通过phonegap给我调试提示。我在android上使用phonegap开发应用程序,并在使用它时一直关注控制台。
答案 0 :(得分:1)
您可以在应用中使用 factory ,如下所示:
.factory("serviceName", function() {
var playlists = [{
title: 'Reggae',
id: 1
}, {
title: 'Chill',
id: 2
}, {
title: 'Dubstep',
id: 3
}, {
title: 'Indie',
id: 4
}, {
title: 'Rap',
id: 5
}, {
title: 'Cowbell',
id: 6
}];
var _myVariableValue = 123;
return {
myPlayList: function() {
return playlists;
},
getValue: function() {
return _myVariableValue;
}
};
})
并拨打 controller
.controller('PlaylistsCtrl', function($scope, serviceName) {
$scope.playlists = serviceName.myPlayList();
$scope.myvariablevalue = serviceName.getValue();
})