Component:
crudModule.js
var crudModule = angular.module('crudModule', ['ui.router', 'smart-table', 'ngCookies', 'ui.bootstrap', 'angularModalService', 'dialogs', 'remoteValidation']);
angular.module('crudModule').component('applicationInfo', {
templateUrl: 'infoApplication.html',
controller: 'applicationInfoCtrl'
});
applicationInfoCtrl.js:
var crudModule = angular.module('crudModule')
crudModule.controller('applicationInfoCtrl', ['httpService', '$scope', function($http, $scope, $cookies, $stateParams, httpService) {
httpService.httpGetRequest("http://localhost:8080/applications/" + $stateParams.id).then(function success(response) {
$scope.application = response.data;
});
$scope.getApiKey = function () {
httpService.httpGetRequest('http://localhost:8080/applications/generateApiKey').then(function success(response) {
$scope.application.apikey = response.data.apikey;
$scope.application.apisecret = response.data.apisecret
})
};
$scope.send = function (object, url) {
httpService.httpPostRequest(object, url + "/" + $stateParams.id).catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
}).then(function success(response){
});
}
}]);
httpService.js:
var crudModule = angular.module('crudModule')
crudModule.factory('httpService', function($http) {
return {
httpGetRequest: function (url) {
return $http({
method: 'GET',
url: url
})
},
httpPostRequest: function (object, url){
return $http({
method:'POST',
url: url,
data: object
})
}
}
});
I am getting error:
Cannot read property 'httpGetRequest' of undefined.
I have injected my httpService and i dont find any mistakes yet
The problem is the order of parameters in your controller, it should be
crudModule.controller('applicationInfoCtrl', ['$http','httpService', '$scope','$cookies','$stateParams' function(http,httpService, $scope,$cookies,$stateParams) {
}
Related
i created this site using django rest framework so that it works without refreshing the page at all,
http://192.241.153.25:8000/#/post/image3
and using angular js's route function was great choice of building a single page app.
but for some reason, the comment box doesn't seem to work possibly because it is put inside the angular js's template.
it throws me csrf token missing error even though the token is included.
judging by the fact that {% csrf token %} tag is visible as a text makes me think that the angular template cannot read the django tag.
could anyone tell me why the comment form isn't functioning and how i can fix this?
(function() {
angular.module('app', ['ngRoute', 'ngResource'])
.controller('FilesListCtrl', ['$scope','$http', function($scope, $http) {//this one controller is new
angular.forEach($scope.posts, function(_post){
$scope.styles = producePostStyle(_post)
});
function producePostStyle(post) {
return { "background-image": "url(" + post.image + ")" }
}
$scope.producePostStyle = producePostStyle;
$http.get('/api/posts/').then(function (response) {
$scope.viewStyle = {
background: 'url('+response.data.results.image+')'
};
});
$scope.images = [];
$scope.next_page = null;
var in_progress = true;
$scope.loadImages = function() {
//alert(in_progress);
if (in_progress){
var url = '/api/posts/';//api url
if ($scope.next_page) {
url = $scope.next_page;
}
$http.get(url).success(function(data) {
$scope.posts = $scope.posts.concat(data.results);//according to api
$scope.next_page = data.next;//acccording to api
if ( ( $scope.next_page == null ) || (!$scope.next_page) ) {
in_progress = false;
}
});
}
};
$scope.loadImages();
}])
angular.module('app')
.controller('profile_image', ['$scope','$http', function($scope, $http) {//this one controller is new
$http({
url: '/api/users/profile/',
method: "GET",
params: {username: 'lifeto'}
}).then(function successCallback(response) {
console.log("Profile Image");
console.log(response);
$scope.lifeto_img = response.data;
}, function errorCallback(response) {
console.log("Error fetching profile image!");
});
}])
.directive('whenScrolled', function($document) {//another directive
return function(scope, elm, attr) {
var raw = elm[0];
$document.bind('scroll', function() {
if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
scope.$apply(attr.whenScrolled);
}
});
};
})
.config(function($resourceProvider, $routeProvider, $httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
// Don't strip trailing slashes from calculated URLs
$resourceProvider.defaults.stripTrailingSlashes = false;
$routeProvider
.when('/', {
template: '<posts></posts>'
})
.when('/posts', {
template: '<posts></posts>'
})
.when('/post/:postId', {
template: '<post></post>'
})
.otherwise({
redirectTo: '/'
});
});
angular.module('app')
.constant('API_URL', '/api/posts/');
angular.module('app')
.factory('Posts', function($resource, API_URL) {
return $resource(API_URL, {format: 'json'}, {
queryPosts: {
method: 'GET',
isArray: false
},
getPostInfo: {
url: API_URL + ':postId/',
method: 'GET',
isArray: false,
params: {
postId: '#postId',
format: 'json'
}
}
});
});
angular.module('app')
.directive('post', function() {
return {
restrict: 'E',
templateUrl: '/static/post.html',
scope: {},
controller: function($scope, $routeParams, Posts) {
$scope.post = null;
function clean(id) {
return id.toLowerCase().replace(/\s/g, "-");
}
function _initialize() {
Posts.getPostInfo({
postId: clean($routeParams.postId)
})
.$promise
.then(function(result) {
$scope.post = result;
console.log(result)
});
}
_initialize();
}
};
});
angular.module('app')
.directive('posts', function() {
return {
restrict: 'E',
templateUrl: '/static/posts.html',
scope: {},
controller: function($scope, Posts) {
$scope.posts = [];
function _initialize() {
Posts.queryPosts().$promise.then(function(result) {
$scope.posts = result.results;
});
}
_initialize();
}
};
});
})();
Since you added
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$http will take care of csrf.
Now you can post data using $http
$http({
method: 'POST',
url: '/url/',
data: {
"key1": 'value1',
},
}).then(function successCallback(response) {
#do
},
function errorCallback(response) {
#do
});
Note: Dont use Ajax Post here. For that you have to do some csrf things other than this.
I've been scratching my head over this one for a couple hours now, and after a good amount of searching I haven't found a helpful solution.
As the title state, my dependencies are not being resolved by Angular's route provider. This is the error:
Unknown provider: testServiceProvider <- testService <- testService
My compiled Javascript file (app.js) looks like this:
'use-strict';
var app = angular.module('test-app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController',
resolve: {
testService: function (testService) {
console.log(testService.message);
}
}
})
}]);
app.factory('apiService', ['$http', function ($http) {
function url(endpoint) {
return '/api/v1' + endpoint;
}
return {
user: {
authenticated: function () {
return $http({method: 'GET', url: url('/user/authenticated')});
},
login: function (token) {
return $http({method: 'GET', url: url('/user/login'), cache: false, headers: {
Authorization: 'Basic ' + token
}});
},
logout: function () {
return $http({method: 'GET', url: url('/user/logout')});
},
model: function () {
return $http({method: 'GET', url: url('/user/data')});
}
}
};
}]);
app.factory('testService', function () {
return {
message: 'Hello world'
};
});
app.controller('HomeController', ['$scope', '$http', function ($scope, $http, apiService, testService) {
$scope.user = {
authenticated: false,
error: '',
username: '',
password: ''
};
$scope.login_button = 'Log in';
$scope.isAuthenticated = function () {
return $scope.user.authenticated;
}
$scope.needsAuthentication = function () {
if (!$scope.user.authenticated) {
return true;
}
return false;
}
$scope.logIn = function ($event) {
$event.preventDefault();
$scope.login_button = 'Please wait...';
var token = btoa($scope.user.username + ':' + $scope.user.password);
apiService.user.login(token).then(function (success) {
$scope.user = success.data.user;
$scope.user.authenticated = true;
}, function (error) {
$scope.user.error = 'Please try logging in again.';
$scope.login_button = 'Log in';
});
};
}]);
As far as I can tell, everything should be resolving fine; am I missing or misunderstanding something?
I think the problem in an alias. You use testService as alias for your resolving. $injector could be confused. Try to rename it for example:
resolve: { testData: function (testService) { console.log(testService.message); } }
and rename it in controller as well.
You have to inject the service,
change
From:
app.controller('HomeController', ['$scope', '$http', function ($scope, $http, apiService, testService)
To:
app.controller('HomeController', ['$scope', '$http','apiService','testService' ,function ($scope, $http, apiService, testService)
I programme an application in ASP.NET MVC6, angularjs and Bootstap.
I want reload a page after bootstrap modal closing.
To do this, I use $window.location.href but it's undefined.
This is my method in angular Controller:
angular
.module('LSapp')
.controller('CustomersCtrl', CustomersCtrl);
CustomersCtrl.$inject = ['$scope', '$http', '$location', '$modal', '$templateCache', '$window'];
function CustomersCtrl($scope, $http, $location, $modal, $window) {
$scope.edit = function(id)
{
var customer = getCustomer(id);
console.log('Customer => FirstName : ' + customer.FirstName);
var reqEditCustomer = $http({ url: '/api/customers/', dataType: 'json', method: 'PUT', data: JSON.stringify(customer), contentType: 'application/json; charset=utf-8' });
reqEditCustomer.success(function (dataResult) {
$scope.customer = dataResult;
$scope.cancel();
});
$scope.customers = getListCustomers();
$window.location.href = '/';
}
}
All runs except the redirection.
I hope someone can help me . Any help is welcome.
you can use
$location.path('/');
instead of
$window.location.href = '/';
Try This -
$location.path('/').replace();
if(!$scope.$$phase) $scope.$apply()
I tried to redirect since a view and not a modal. It's work.
So I think it's redirect with my modal who create problem.
It's my full controller:
(function () {
'use strict';
angular
.module('LSapp')
.controller('CustomersCtrl', CustomersCtrl)
.controller('CustomersGetCtrl', CustomersGetCtrl);
CustomersCtrl.$inject = ['$scope', '$http', '$location', '$modal', '$templateCache', '$window'];
function CustomersCtrl($scope, $http, $location, $modal, $window) {
/*---------------------------------------------------------------------------------
* Obtain Customer List
*--------------------------------------------------------------------------------*/
function getListCustomers()
{
var reqCustomers = $http.get('/api/Customers');
reqCustomers.success(function (dataResult) {
$scope.customers = dataResult;
});
return $scope.customers;
}
getListCustomers();
/*---------------------------------------------------------------------------------
* Obtain Customer by ID
*--------------------------------------------------------------------------------*/
function getCustomer(id) {
var reqGetCustomer = $http({ url: '/api/customers/' + id, method: 'GET' });
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
})
return $scope.customer;
}
$scope.edit = function(id)
{
var customer = getCustomer(id);
console.log('Customer => FirstName : ' + customer.FirstName);
var reqEditCustomer = $http({ url: '/api/customers/', dataType: 'json', method: 'PUT', data: JSON.stringify(customer), contentType: 'application/json; charset=utf-8' });
reqEditCustomer.success(function (dataResult) {
$scope.customer = dataResult;
$scope.cancel();
});
$scope.customers = getListCustomers();
//This is that I tried to redirect
//$window.location.href = '/';
//$location.path('/').replace();
//if(!$scope.$phase) $scope.$apply
}
/*---------------------------------------------------------------------------------
* Manage Customer Details Modal
*--------------------------------------------------------------------------------*/
$scope.openDetails = function (id) {
var modalInstance = $modal.open({
templateUrl: 'Modals/Customers/details.html',
controller: $scope.modalDetails,
resolve: {
id: function () {
return id
}
}
});
}
$scope.modalDetails = function($scope, $modalInstance, id)
{
if (angular.isDefined(id)) {
var reqGetCustomer = $http({ url: '/api/Customers/' + id, method: 'GET' });
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
});
} else { alert('id is undefined'); }
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
}
}
/*---------------------------------------------------------------------------------
* Manage Customer Edit Modal
*--------------------------------------------------------------------------------*/
$scope.openEdit = function (id) {
var modalInstance = $modal.open({
templateUrl: 'Modals/Customers/edit.html',
controller: $scope.modalEdit,
resolve: {
id: function () {
return id
}
}
});
}
$scope.modalEdit = function ($scope, $modalInstance, id) {
if (angular.isDefined(id)) {
var reqGetCustomer = $http({ url: '/api/Customers/' + id, method: 'GET' });
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
});
} else { alert('id is undefined'); }
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
}
}
}
//Controller to redirect since View
CustomersGetCtrl.$inject = ['$scope', '$http', '$routeParams', '$window'];
function CustomersGetCtrl($scope, $http, $routeParams, $window)
{
function getCustomer()
{
var reqGetCustomer = $http({ url: '/api/customers/' + $routeParams.id, method: 'GET' })
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
})
}
getCustomer();
$scope.edit = function () {
$window.location.href = '/';
}
}
})();
I solved the problem by using ui.router instead of ng -router.
I have tried to build a service that will return a $resource after the service has authenticated.
I have done it like this:
.factory('MoltinApi', ['$q', '$resource', '$http', 'moltin_options', 'moltin_auth', function ($q, $resource, $http, options, authData) {
var api = $resource(options.url + options.version + '/:path', {
path: '#path'
});
var authenticate = function () {
if (!options.publicKey)
return;
var deferred = $q.defer();
var request = {
method: 'POST',
url: options.url + 'oauth/access_token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: "grant_type=implicit&client_id=" + options.publicKey
};
$http(request).success(function (response) {
authData = response;
deferred.resolve(api);
});
return deferred.promise;
};
return authenticate();
}])
But I can not call the resource in my controller:
.controller('HomeController', ['MoltinApi', function (moltin) {
var self = this;
moltin.get({ path: 'categories' }, function (categories) {
console.log(categories);
});
}]);
it just states that 'undefined is not a function'.
Can someone tell me what I am doing wrong?
Update 1
So after playing with the solution that was suggested, this is the outcome.
angular.module('moltin', ['ngCookies'])
// ---
// SERVICES.
// ---
.factory('MoltinApi', ['$cookies', '$q', '$resource', '$http', 'moltin_options', function ($cookies, $q, $resource, $http, options) {
var api = $resource(options.url + options.version + '/:path', {
path: '#path'
});
var authenticate = function () {
if (!options.publicKey)
return;
var deferred = $q.defer();
var authData = angular.fromJson($cookies.authData);
if (!authData) {
console.log('from api');
var request = {
method: 'POST',
url: options.url + 'oauth/access_token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: "grant_type=implicit&client_id=" + options.publicKey
};
deferred.resolve($http(request).success(function (response) {
$cookies.authData = angular.toJson(response);
setHeaders(response.access_token);
}));
} else {
console.log('from cookie');
deferred.resolve(setHeaders(authData.access_token));
}
return deferred.promise;
};
var setHeaders = function (token) {
$http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}
return authenticate().then(function (response) {
return api;
});
}]);
and to call it I have to do this:
.controller('HomeController', ['MoltinApi', function (moltin) {
var self = this;
moltin.then(function (api) {
api.get({ path: 'categories' }, function (categories) {
console.log(categories);
self.sports = categories.result;
});
});
}]);
but what I would like to do is this:
.controller('HomeController', ['MoltinApi', function (moltin) {
var self = this;
moltin.get({ path: 'categories' }, function (categories) {
console.log(categories);
}, function (error) {
console.log(error);
});
}]);
As you can see, the service is checking to see if we have authenticated before returning the API. Once it has authenticated then the API is returned and the user can then call the api without having to authenticate again.
Can someone help me refactor this service so I can call it without having to moltin.then()?
You are returning the authenticate function call in the MoltinApi factory, so you are returning the promise. And the method get doesn't exist in the promise
I'm not quite sure what I'm doing wrong, but it seems that my profile doesn't resolve by the time we get to the MainCtrl. The user however does, resolve. Am I, perhaps not fetching the profile information properly in the Auth Service?
Router:
angular.module('app')
.config(function ($stateProvide) {
$stateProvider
.state('main', {
url: '/main',
templateUrl: 'app/main/main',
controller: 'MainCtrl',
resolve: {
user: function (Auth) {
return Auth.getUser();
},
profile: function (user) {
return Auth.getProfile();
}
}
});
});
Controller:
angular.module('app')
.controller('MainCtrl', function ($scope, user, profile) {
$scope.user = user;
$scope.profile = profile; <- DOESNT RESOLVE
});
Auth Service:
angular.module('app')
.factory('Auth', function ($firebaseSimpleLogin, $firebase, FBURL) {
var ref = new Firebase(FBURL);
var auth = $firebaseSimpleLogin(ref);
var Auth = {
user: {},
getUser: function () {
return auth.$getCurrentUser();
},
getProfile: function(uid) {
return $firebase(ref.child('users').child(uid)).$asObject();
}
};
return Auth;
});
Something like
auth.$getCurrentUser()
returns a promise so you need a
.then(function(user) {
event before your callback complete
In your case you may just resolve on the then, something like
Auth.getUser().then(function(user){ return user; });
Also $asObject() needs $loaded() for it's promise
var obj = $firebase(ref).$asObject();
obj.$loaded()
.then(function(data) {})
Try this structure for your promises:
var fetchSomething = function (action, params) {
var promise = $http({
method: 'POST',
url: 'someurl to the firebase',
data: params,
headers: {
'Access-Control-Allow-Origin': true,
'Content-Type': 'application/json'
}
}).success(function (data, status, headers, config) {
return data;
});
return promise;
};