0
我創建了一個Angular應用程序,併爲我的控制器添加了一些基本代碼,可以在下面看到。我現在試圖包含兩個服務,這些服務是在我的services.js文件中創建的,該文件正在我的index.html文件中加載,並且在我的controllers.js文件中是必需的。出於某種原因,我無法訪問任何通過的命名空間,我似乎無法弄清楚爲什麼會發生這種情況,因爲我沒有看到任何錯誤,並且大部分教程或示例都顯示了相同的設置。有人有主意嗎?謝謝:)無法在我的控制器中使用Angular加載服務
Controllers.js
angular.module('starter.controllers', ['services'])
.controller('AppCtrl', function($scope, $ionicModal, $timeout, Auth, socket) {
// Form data for the login modal
$scope.loginData = {};
debugger // i dont have access to Auth or socket
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
// Triggered in the login modal to close it
$scope.closeLogin = function() {
$scope.modal.hide();
};
// Open the login modal
$scope.login = function() {
$scope.modal.show();
};
// Perform the login action when the user submits the login form
$scope.doLogin = function(user) {
console.log('Doing login', $scope.loginData);
debugger // I dont have access to Auth or socket
// Simulate a login delay. Remove this and replace with your login
// code if using a login system
$timeout(function() {
$scope.closeLogin();
}, 1000);
};
})
Services.js
var baseUrl = 'http://localhost:3000';
angular.module('services', [])
.factory('socket', function socket($rootScope) {
var socket = io(baseUrl);
return {
on: function(eventName, cb) {
socket.on(eventName, function() {
var args = arguments;
$rootScope.$apply(function() {
cb.apply(socket, args);
});
});
},
emit: function(eventName, data, cb) {
socket.emit(eventName, data, function() {
var args = arguments;
$rootScope.$apply(function() {
if (cb) cb.apply(socket, args);
});
});
}
};
})
.factory('Auth', function Auth($q, $http) {
var user = null;
var login = function login (name, password) {
var defer = $q.defer();
var url = baseUrl + '/login';
var postData = { name: name, password: password };
$http.post(url, postData).success(function(response) {
if (response.success && response.success === true) {
user = { name: response.name, id: response.id };
window.localStorage.setItem('user', JSON.stringify(user));
return defer.resolve(response);
} else {
return defer.resolve('No user found');
}
}).error(function(err) {
defer.reject(err);
});
return defer.promise;
}
var currentUser = function currentUser (user) {
return user;
}
var logout = function logout() {
user = null;
window.localStorage.removeItem('user');
}
return {
login: login,
logout: logout,
currentUser: currentUser
};
});
是你的代碼縮小了嗎? – Claies
控制檯說什麼?在index.html中構建包含service.js文件的系統? – cheekybastard
適用於我:http://plnkr.co/edit/iCAt5LaXkYpLY8Fj9qJa?p=preview –