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);
}]
}
Related
I'm trying to access factory service within controller to obtain correct data.
Related controller code looks like:
myApp.controller('RegistrationController', ['$scope','$routeParams','$rootScope','$location','$filter','$mdDialog','checkAttendee', function($scope, $routeParams, $rootScope, $location, $filter, $mdDialog,checkAttendee){
...
$scope.addAttendee = function(ev) {
$mdDialog.show({
controller: AddDialogCntrl,
templateUrl: 'views/regForm.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
controllerAs: 'ctrl',
fullscreen: $scope.customFullscreen, // Only for -xs, -sm breakpoints.
locals: {parent: $scope}
})
.then(
function(response){
if(angular.isDefined(response)){
attendees.push(response);
checkAttendee.getAttendeeInfo(response);
}
},
function(){
//no changes
}
)
.catch(
function(error) {
console.log('Error: ' + error);
}
)
};
and factory service code
myApp.factory('checkAttendee', ['$http', function($http) {
this.getAttendeeInfo = function(req) {
return $http.get("/check/attendee/", {params:{"firstName":req.firstName, "lastName":req.lastName, "email": req.email, "eventID": req.eventID}})
.then(function(response) {
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
console.log('Data: ' + data);
console.log('Status: ' + status);
return data;
})
.catch(function(response) {
console.log('something worng');
});
}
}]);
but that combination gives me an error Provider 'checkAttendee' must return a value from $get factory method. when there is a return value.
Any thoughts?
Option 1
When we work with factories the structure should be:
myApp.factory('checkAttendee', ['$http', function($http) {
var factory = {
getAttendeeInfo : function () {
return $http.get(/**/).then(function(response) {
// ..
return data;
}
}
}
return factory;
}]);
DEMO 1
Option 2
you can change factory to service and everything should work. A.e.:
myApp.service('checkAttendee', ['$http', function($http) {
this.getAttendeeInfo = function(req) {
return $http.get("/check/attendee/", {params:{"firstName":req.firstName, "lastName":req.lastName, "email": req.email, "eventID": req.eventID}})
.then(function(response) {
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
console.log('Data: ' + data);
console.log('Status: ' + status);
return data;
})
.catch(function(response) {
console.log('something worng');
throw response;
});
}
}]);
DEMO 2
Keep in mind that service extends the factory
I have an app where my main state makes a resolve makes an http call and fetches an array.
Then, the child array is supposed to display one object from this array, but it seems that the variables from the controller are defined too early and don't get updated properly, so the child comes out empty.
I've tried it without http call (var array = [array]), and it works fine, but not with the http call.
Any tips on how to fix this?
Here's the controllers:
.controller('appCtrl',['$scope', 'SearchService','fair', function($scope, SearchService, fair){
$scope.data = SearchService;
$scope.datafairs = $scope.data.flatexhibitors;
console.log($scope.datafairs);
}])
.controller('ChildController',['$scope', 'exhibitor', '$filter', function($scope, exhibitor, $filter){
$scope.$watch(function() { return $scope.fair; }, function(newVal) {
$scope.fairs = newVal;
console.log($scope.fairs);
$scope.chosenexhibitor = $filter("filter")($scope.fairs, {'slug':exhibitor}, true);
}, true);
}])
The service:
.factory("SearchService", function($http) {
var service = {
flatexhibitors : [],
datafairs : [],
getAllExhibitors : function (wop) {
var searchindex = wop;
console.log(searchindex);
var url = '../register/backend/databaseconnect/getexhibitors.php';
var config = {
params: {
search: searchindex
},
cache:true
};
$http.get(url, config).then(function (data) {
service.datafairs = data.data.rows;
for (var i in service.datafairs) {
service.flatexhibitors.push(service.datafairs[i].doc);
};
return service.flatexhibitors;
});
}
}
return service;
})
And the states:
.config(function($stateProvider) {
$stateProvider.state('berliner', {
url: '/berlinerliste',
params : {search: 'Berliner 2017'},
resolve: {
fair: function(SearchService, $stateParams) {
return SearchService.getAllExhibitors($stateParams.search);
}
},
views: {
'header': {
templateUrl: 'header.htm'
},
'main':{
templateUrl: 'bl2017.htm',
controller: 'appCtrl'
}
}
})
.state('berliner.exhibitor', {
url: '/{id}',
resolve: {
exhibitor: function($stateParams) {
var slug = $stateParams.id;
return slug;
}
},
views: {
'header': {
templateUrl: 'header.htm'
},
'wop':{
templateUrl: 'exhibitor.htm',
controller: 'ChildController'
}
}
})
})
I've managed to replicate the issue in a Plunkr.
Change the getAllExhibitors to return a promise like below:
getAllExhibitors : function (wop) {
var searchindex = wop;
console.log(searchindex);
var url = '../register/backend/databaseconnect/getexhibitors.php';
var config = {
params: {
search: searchindex
},
cache:true
};
return $http.get(url, config).then(function (data) {
service.datafairs = data.data.rows;
for (var i in service.datafairs) {
service.flatexhibitors.push(service.datafairs[i].doc);
};
return service.flatexhibitors;
});
}
This is my app.js
angular.module('app', ['ui.router', 'satellizer'])
.constant('API_URL', 'http://localhost/angular/public/api/v1/')
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
$authProvider.loginUrl = 'angular/public/api/authenticate';
$urlRouterProvider.otherwise('/auth');
$stateProvider
.state('auth', {
url: '/auth',
templateUrl: 'app/view/login.html',
controller: 'AuthController as auth'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'app/view/dashboard.tmpl.html',
params: {
model: ''
}
})
.state('dashboard.employees', {
templateUrl: 'app/view/employee.tmpl.html',
controller: 'employeesController',
}).state('dashboard.test', {
templateUrl: 'app/view/edit.tmpl.html',
controller: 'employeesController',
})
});
When I click ui-sref="dashboard.employees" controller calls twice.
calls twice
This is my controller which I want to use for all views. I developed cms on laravel and angular. I can't create a new controller for every table entity.
angular.module('app')
.controller('employeesController', function($scope, $http, API_URL,$stateParams) {
//retrieve employees listing from API
$scope.employees = '';
$http.get(API_URL + $stateParams.model)
.success(function(response) {
$scope.employees = response;
});
//show modal form
$scope.toggle = function(modalstate, id) {
$scope.modalstate = modalstate;
switch (modalstate) {
case 'add':
$scope.form_title = "Add New Employee";
break;
case 'edit':
$scope.form_title = "Employee Detail";
$scope.id = id;
$http.get(API_URL + $stateParams.model+'/' + id)
.success(function(response) {
console.log(response);
$scope.employee = response;
});
break;
default:
break;
}
$('#myModal').modal('show');
}
//save new record / update existing record
$scope.save = function(modalstate, id) {
var url = API_URL + "employees";
//append employee id to the URL if the form is in edit mode
if (modalstate === 'edit') {
url += "/" + id;
}
console.log('saved');
$http({
method: 'POST',
url: url,
data: $.param($scope.employee),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(response) {
var index = _.findIndex($scope.employees, function(b) {
return b.id == $scope.employee.id;
});
console.log(index);
if (index != -1) {
$scope.employees[index] = $scope.employee;
} else {
console.log($scope.employee);
$scope.employee.id = response;
$scope.employees.push($scope.employee);
console.log($scope.employees);
}
$('#myModal').modal('toggle');
}).error(function(response) {
console.log(response);
alert('This is embarassing. An error has occured. Please check the log for details');
});
}
//delete record
$scope.confirmDelete = function(employee) {
var isConfirmDelete = confirm('Are you sure you want this record?');
if (isConfirmDelete) {
$http({
method: 'DELETE',
url: API_URL + 'employees/' + employee.id
}).
success(function(data) {
_.remove($scope.employees, function(n) {
return n.id == employee.id;
});
console.log(data);
}).
error(function(data) {
console.log(data);
alert('Unable to delete');
});
} else {
return false;
}
}
});
Where is my mistake? How can I fix that?
kindly check, if you are called the controller in your employee.tmpl.html page, like ng-controller="employeesController"
Please remove it, if you call the ng-controller in your html
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.
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;
}
};
});