How to make a service call with a Angular-ui modal instance - angularjs

I am switching to a Angular-ui modal and I am confused on how to make a $http get call and return the results. I have been using a different angular modal with the current code. I understand ow this is working but I need some help on the transition. thanks
This is the modal I am currently using. this works fine. I need to apply this to the Angular-UI modal
$scope.editCivilCaseModal = function (id) {
var deferred = $q.defer();
$http({ method: 'get', url: '/api/apiCivilCase/' + id })
.success(function (civilCase) {
deferred.resolve(civilCase);
console.log(civilCase);
$scope.active = civilCase;
$scope.openEditCivilCaseModal = $ekathuwa.modal({
scope: $scope,
contentPreSize: "lg",
templateURL: "views/modals/editCivilCaseModal.html"
});
//show modal window
$scope.openEditCivilCaseModal.then(function (m) {
m.modal('show');
});
}).error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
need to switch to this
.controller('ModalDemoCtrl', function ($scope, $modal, $log) {
$scope.items = ["item1", "item2", "item3"];
$scope.open = function (id) {
var modalInstance = $modal.open({
templateUrl: "views/modals/editCivilCaseModal.html",
controller: 'ModalInstanceCtrl',
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then((function (selectedItem) {
$scope.selected = selectedItem;
}), function () {
$log.info("Modal dismissed at: " + new Date());
});
};
}
).controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss("cancel");
};
}
Solution per the suggested solution
//Edit Civil Modal
$scope.editCivilCaseModal = function (id) {
var deferred = $q.defer();
$http({ method: 'get', url: '/api/apiCivilCase/' + id })
.success(function (civilCase) {
deferred.resolve(civilCase);
console.log(civilCase);
$scope.active = civilCase;
}).error(function (error) {
deferred.reject(error);
}).then(function () {
$modal.open({
templateUrl: "views/modals/editCivilCaseModal.html",
controller: 'ModalInstanceCtrl',
resolve: {
active: function () {
return $scope.active;
}
}
});
})
return deferred.promise;
}
.controller('ModalInstanceCtrl', function ($scope, $modalInstance, active) {
$scope.active = active
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss("cancel");
};
});

you should split your $http call
$scope.editCivilCaseModal = function (id) {
var deferred = $q.defer();
$http({ method: 'get', url: '/api/apiCivilCase/' + id })
.success(function (civilCase) {
deferred.resolve(civilCase);
console.log(civilCase);
$scope.active = civilCase;
}).error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
and on success of http do whatever you like opening the model.
$scope.editCivilCaseModel().then(function(){
$scope.openEditCivilCaseModal = $ekathuwa.modal({
scope: $scope,
contentPreSize: "lg",
templateURL: "views/modals/editCivilCaseModal.html"
});
//show modal window
$scope.openEditCivilCaseModal.then(function (m) {
m.modal('show');
});
})
this is just to give you the concept because I am not able to see the exact relationship between now and expected.

Related

django rest framework comment form not working

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.

how to load more than one service in $state resolve?

I want to load two APIs before page is going to load For it i have used the following code in $stateProvider
.state('admin-panel.default.jobadd', {
url: '/jobadd/:jobID',
templateUrl: 'app/search/jobadd.tmpl.html',
controller: 'JobaddController',
resolve: {
jobAdd: ['Search', '$stateParams','$q', function(Search,$stateParams,$q) { //Search is service
var jobAdd = Search.jobAdd($stateParams.jobID);
var isApplied = Search.is_job_applied($stateParams.jobID);
jobAdd.$promise.then(function(response) {console.log('Resource 1 data loaded!')});
isApplied.$promise.then(function(response) {console.log('Resource 2 data loaded!')});
return $q.all([jobAdd.$promise, isApplied.$promise]);
}]
},
data: {
requireLogin: true
}
});
})
But it's not give the data when injects to the controller, page seems as blank
my controller code is
.controller('JobaddController', function ($scope, $mdDialog, $state, jobAdd, Profile) {
$scope.jobs = jobAdd[0];
$scope.benifits = jobAdd[0].benifits;
if($scope.jobs.short_listed == 1)
$scope.jobs.flag = true;
else
$scope.jobs.flag = false;
$scope.checkShortList= function(job){
if(job.flag){
Profile.rmShortList(job.short_list_id);
job.flag = false;
}
else{
if(job.short_list_id === null){
Profile.addNewShortList(job.id).then(function(response){
job.short_list_id = response.short_list_id;
});
}
else
Profile.addShortList(job.short_list_id,job.id);
job.flag = true;
}
};
$scope.companyModal = function(ev) {
$mdDialog.show({
controller: 'CompanyDetailsController',
templateUrl: 'app/search/company-details.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
})
.then(function(answer) {
$scope.alert = 'You said the information was "' + answer + '".';
}, function() {
$scope.alert = 'You cancelled the dialog.';
});
};
$scope.applyModal = function(ev) {
$mdDialog.show({
controller: 'ApplyController',
templateUrl: 'app/search/apply.tmpl.html',
locals: { Jobid: $scope.jobs.id },
parent: angular.element(document.body),
targetEvent: ev,
resolve: {
shortProfile: ['Profile', function(Profile) {
return Profile.shortProfile();
}]
},
})
.then(function(answer) {
$scope.alert = 'You said the information was "' + answer + '".';
}, function() {
$scope.alert = 'You cancelled the dialog.';
});
};
var container = angular.element(document.getElementById('container'));
var section2 = angular.element(document.getElementById('section-2'));
$scope.toTheTop = function() {
container.scrollTop(0, 5000);
};
$scope.toSection2 = function() {
container.scrollTo(section2, 0, 1000);
};
})
in service code
.service('Search', [ '$http', '$q', 'API',
function($http, $q, API) {
var data = '';
this.jobAdd = function(job_id) {
var def = $q.defer();
$http({
url: API.url+'get_job_add_detail?job_id=' + job_id,
method: "GET"
}).success(function(response) {
if(response.status == 'Success'){
data = response.data;
def.resolve(data);
}
}).error(function(response) {
console.log (response);
if(response.status == 'Failed'){
data = response.msg;
def.reject(data);
}
});
return def.promise;
}
this.isJobApplied = function(job_id) {
var def = $q.defer();
$http({
url: API.url+'is_job_applied?job_id='+job_id,
method: "GET",
}).success(function(response) {
if(response.status == 'Success'){
data = response.data;
def.resolve(data);
}
}).error(function(response) {
console.log (response);
if(response.status == 'Failed'){
data = response.msg;
def.reject(data);
}
});
return def.promise;
}
}]);
What's the wrong here?? how to attach more than on service in $state resolve?
simply you can for more than one service.
resolve: {
jobAdd: ['Search', '$stateParams', function(Search,$stateParams) {
return Search.jobAdd($stateParams.jobID);
}],
isApplied: ['Search', '$stateParams', function(Search,$stateParams) {
return Search.isJobApplied($stateParams.jobID);
}]
}

$window.location.href is undefined with angularjs

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.

Angular controller won't update the view for some reason

I have a service that looks like:
myApp.service('peerService', [
'$http', function($http) {
this.getPeers = function() {
return $http({
url: '/api/v1/peers',
method: 'GET'
});
};
}
]);
In my controller, I have:
myApp.controller('PeerComparisonController', [
'$scope', '$rootScope', 'peerService', function($scope, $rootScope, peerService) {
$scope.init = function() {
$rootScope.pageTitle = 'Peer Comparison';
return $scope.peers = [];
};
$scope.getPeers = function() {
return peerService.getPeers().then(function(response) {
console.log(response);
return $scope.peers = response.data;
});
};
return $scope.init();
}
]);
My view has {{ peers }} in it. This does not get updated when the service returns. I've tried:
peerService.getPeers().then(function(response) {
return $scope.$apply(function() {
return $scope.peers = response.data;
});
});
And that also doesn't work. So any ideas?
you try something like this
myApp.service('peerService', [
'$http', function($http) {
this.getPeers = function() {
return $http({method: 'GET', url:'/api/v1/peers'}).
then(function(response) {
return response.data;
});
};
}
]);
or
myApp.service('peerService', ['$http', function ($http) {
this.getPeers = function () {
var deferred = $q.defer();
$http({ method: 'GET', url: '/api/v1/peers' }).
then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
};
}
]);

resolve firebase data using ui-route

I'm new in angular/ui-route and firebase.
Do you know if it's possible to resolve firebase data using ui-route ?
I tryed the following states :
.state('contacts', {
abstract: true,
url: '/contacts',
templateUrl: './assets/app/views/contacts/contacts.html',
resolve: {
contacts: ['contacts',
function( contacts){
return contacts.all();
}],
contactsFb: WHAT TO SET ???
},
controller: ['$scope', '$state', 'contacts', 'utils', 'contactsFb',
function ( $scope, $state, contacts, utils, contactsFb) {
// Working Fine but not from firebase
$scope.contacts = contacts;
// Can't make it works... :-(
$scope.contacts = contactsFb;
}]
})
Here is the factory:
.factory('contactsFb', function($firebase) {
var url='https://evet.firebaseio.com/contacts';
return $firebase(new Firebase(url));
})
.factory('contacts', ['$http', function ($http, utils) {
var path = './assets/app/models/contacts.json';
var contacts = $http.get(path).then(function (resp) {
return resp.data.contacts;
});
var factory = {};
factory.all = function () {
return contacts;
};
factory.get = function (id) {
return contacts.then(function(){
return utils.findById(contacts, id);
})
};
return factory;
}])
Can't make it works... :-(
Maybe you can help me ?
Many thanks!
Try something like this:
.state('contacts', {
abstract: true,
url: '/contacts',
templateUrl: './assets/app/views/contacts/contacts.html',
resolve: {
loadContacts: function(contactsFb) {
return contactsFb.promiseToHaveContacts();
}
},
controller: function ($scope, contactsFb) {
$scope.contacts = contactsFb.contacts;
}
})
.factory('contactsFb', function($firebase, $q) {
return {
contacts: null,
promiseToHaveContacts: function() {
var deferred = $q.defer();
if (this.contacts === null) {
this.contacts = $firebase(new Firebase('https://evet.firebaseio.com/contacts'));
this.contacts.$on('loaded', function(loadedData) {
deferred.resolve();
});
}
else {
deferred.resolve();
}
return deferred.promise;
}
};
});

Resources