function not execute in controller and factory - angularjs

i'm developing an app that should call a controller where there are some functions, because i receive from a server (localhost in this moment) a JSON array with a structure like this:
[{
"day": "17/11/2016",
"time": "09:45"
}, {
"day": "17/11/2016",
"time": "16:50"
}, {
"day": "18/11/2016",
"time": "11:25"
}, {
"day": "18/11/2016",
"time": "12:30"
}, {
"day": "21/11/2016",
"time": "16:10"
}, {
"day": "21/11/2016",
"time": "17:25"
}]
And then i print it in two selects in a form in this way:
SELECT 1:
17/11/2016, 18/11/2016, 21/11/2016
SELECT 2:
09:45, 16:50 OR 11:25, 12:30 OR 16:10, 17:25 based on the choice in the first select
Up to this point there are no problems but now it should execute a function that post the coice of the user to the server but the app doesn't execute it.
This is my code,
SCRIPT.JS
angular
.module('demo', [])
.controller('DefaultController', DefaultController)
.factory('dataService', dataService);
DefaultController.$inject = ['dataService'];
function DefaultController(dataService) {
var vm = this;
getEvents();
function getEvents() {
return dataService.getEvents()
.then(function (data) {
vm.data = data;
return vm.data;
});
}
}
dataService.$inject = ['$http'];
function dataService($http) {
var service = {
getEvents: getEvents
};
return service;
function getEvents() {
var config = {
transformResponse: function (data, headers) {
var result = {
events: [],
schedules: []
};
var events = JSON.parse(data);
var dates = [];
for (var i = 0; i < events.length; i++) {
if (dates.indexOf(events[i].day) === -1) {
var date = events[i].day;
dates.push(date);
result.events.push({
date: date
});
}
result.schedules.push({
date: events[i].day,
time: events[i].time
});
}
return result;
}
};
return $http.get('http://<path>/api/apiTimes.php', config)
.then(getEventsCompleted)
.catch(getEventsFailed);
function getEventsCompleted(response) {
return response.data;
}
function getEventsFailed(error) {
console.error(error);
}
}
}
console.log("fine");
function submit ($http){
console.log("funzione");
var data = {};
console.clear();
var link = 'http://<path>/api/apiFix.php';
var mail = window.localStorage.getItem("mail");
$http.post(link, {giorno: data.giorno, ora: data.ora, mail: mail})
.then(function (res){
console.log("Dentro http.post");
var response = res.data;
console.log(response);
});
}
FORM HTML:
<body ng-app="demo" ng-controller="DefaultController as ctrl">
<form ng-submit="submit()">
<div class="list">
<label class="item item-input item-select">
<div class="input-label">
Giorno:
</div>
<select ng-options="event as event.date for event in ctrl.data.events" ng-model="data.giorno">
<option disabled>Seleziona un giorno </option>
</select>
</label>
</div>
<div class="list">
<label class="item item-input item-select">
<div class="input-label">
Ora:
</div>
<select ng-options="schedule as schedule.time for schedule in ctrl.data.schedules | filter: { date: data.giorno.date}" ng-model="data.ora" ng-disabled="!data.giorno">
<option disabled>Seleziona un orario </option>
</select>
</label>
</div>
</div>
</div><br>
<ul class="list">
<li class="item item-toggle">
&Egrave un'urgenza?
<label class="toggle toggle-assertive">
<input type="checkbox">
<div class="track">
<div class="handle"></div>
</div>
</label>
</li>
</ul>
<div align="center">
<input class="button button-calm" type="submit" name="submit" value="Prenota !">
</div>
</form>
</body>
I have no errors in console but the function "submit" it isn't execute.
How can i solve this problem?
Thank's

You have a couple of errors. You need to fix at least these
On your controller (you will need to inject $http)
DefaultController.$inject = ['dataService', '$http'];
function DefaultController(dataService, $http) {
var vm = this;
vm.submit = function (){
console.log("funzione");
var data = vm.form; // IMPORTANT
console.clear();
var link = 'http://<path>/api/apiFix.php';
var mail = window.localStorage.getItem("mail");
$http.post(link, {giorno: data.giorno, ora: data.ora, mail: mail})
.then(function (res){
console.log("Dentro http.post");
var response = res.data;
console.log(response);
});
};
}
And in your form as I mention in the comment, since you are using the controller as approach you need to include ctrl
<form ng-submit="ctrl.submit()">
And rename your ng-model variables to
ng-model="ctrl.form.ora" //ng-model="data.ora"
ng-model="ctrl.form.giorno" //ng-model="data.giorno"

Related

AngularJS multi screen validation on last step

I have an angularJS application. I have implemented a generic workflow using $routeProvider, templateUrl & Controllers.
Each step(screen) is verified when user click on next button and moves to the next step if validation passes. If validation fails user is required to fix all the error, displayed on the screen, before moving to next step.
When user has visited all the screens(passed validation for each screen) all the breadcrumbs get enabled and now user can move freely between those steps/breadcrumbs.
Requirement:
Now I want to allow user to move freely between steps by clicking on the breadcrumbs and when user clicks on the lodge button, on the last step, validation for current as well as for all previous steps should be invoked, and clicking on the error user should be able taken to the relevant step/screen.
Also I want to keep the functionality of validating the individual steps on the click of next button.
As you can see each screen has a separate controller along with the scope.
Once user move from one step to another it can't access the previous scope.
Initially I thought of storing scope of each screen in an array, but once I move between steps new scope is created (as it should) and only current step has a form with valid data model and "valid" flag as false.
Form object at current step
Form object of other screen without and fields attached
I'm not very well versed with Angularjs and trying to get some idea weather
Is it possible what I'm trying to achieve keeping the existing functionality intact. (My understanding is that I can't have a single controller since I need to keep the functionality of validating each step individually)?
Is there a better way to trying to achieve this functionality?
PS: Sadly I can't upgrade to newer version of Angular.
Any help will be highly appreciated.
Form Validation
validator.validate = function($scope, submitCallback, additionalOptions) {
var options = {};
$.extend(options, commonOptions, additionalOptions);
var form = $scope[options.formName];
hideErrorMessages(options.errorContainerSelectorId);
if (form.$valid) {
submitCallback();
return;
}
showErrorMessages({message: composeAngularValidationErrors(form),
errorContainer: $('#' + options.errorContainerSelectorId)});
};
View:
<#assign temp=JspTaglibs["http://www.test.com/tags"]>
<div ng-controller="LodgeApplicationWorkflowController" ng-cloak>
<workflow-breadcrumbs></workflow-breadcrumbs>
{{model | json}}
<div ng-view>
</div>
<script type="text/ng-template" id="applicant-details">
<form name="form" method="post" action="#" class="standard">
<h3>Primary contact details</h3>
<div class="row">
<div class="span3">
<label for="owner-primary-contact">Primary contact:</label>
<select class="span3" id="owner-primary-contact" required name="applicantDetails.primaryContact"
ng-model="model.applicantDetails.primaryContactId"
ng-options="user.id as user.fullName for user in refData.contactInfos"
>
<option value=""></option>
</select>
</div>
<div class="span3">
<label for="owner-primary-contact-phone">Phone:</label>
<input type="text" class="span3" id="owner-primary-contact-phone" name="applicantDetails.primaryContactPhone"
readonly
ng-model="model.applicantDetails.primaryContactPhone"/>
</div>
<div class="span3">
<label for="owner-primary-contact-email">Email:</label>
<input type="text" class="span3" id="owner-primary-contact-email" name="applicantDetails.primaryContactEmail"
readonly
ng-model="model.applicantDetails.primaryContactEmail"/>
</div>
</div>
</form>
</script>
<script type="text/ng-template" id="lgc-methodology">
<form name="form" method="post" action="#" class="standard">
<h3>Describe the Your Methodology</h3>
<div class="row">
<div class="span9">
<label for="methodology">Describe the methodology which you propose to employ:
</label>
<textarea class="span9" id="methodology" name="methodology"
rows="10"
ng-maxlength="4000"
ng-model="model.methodology" required>
</textarea>
</div>
</div>
</form>
</script>
<script type="text/ng-template" id="approval-details">
<form name="form" method="post" action="#" class="standard">
<div class="row" ng-if="model.approvalDetails.planningApprovalsObtained === 'true'">
<div class="span9">
<label for="planning-approvals-details">Approval details:</label>
<textarea class="span6" id="planning-approvals-details"
name="approvalDetails.planningApprovalDetails"
ng-if="model.approvalDetails.planningApprovalsObtained === 'true'"
required ng-maxlength="4000"
ng-model="model.approvalDetails.planningApprovalDetails"></textarea>
</div>
</div>
<div class="row" ng-if="model.approvalDetails.planningApprovalsObtained === 'false'">
<div class="span9">
<label for="planning-approvals-details">Reasons:</label>
<textarea class="span6" id="planning-approvals-details"
name="approvalDetails.planningApprovalDetails"
ng-if="model.approvalDetails.planningApprovalsObtained === 'false'"
required ng-maxlength="4000"
ng-model="model.approvalDetails.planningApprovalDetails"></textarea>
</div>
</div>
<div >
<div class="row" >
<div class="span9">
<label for="environment-approval-details">Approval details:</label>
<textarea class="span6" id="environment-approval-details"
name="approvalDetails.environmentApprovalDetails"
ng-maxlength="4000"
ng-required="model.approvalDetails.environmentApprovalsObtained === 'true'"
ng-model="model.approvalDetails.environmentApprovalDetails"></textarea>
</div>
</div>
<div class="row" ng-if="model.approvalDetails.environmentApprovalsObtained === 'false'">
<div class="span9">
<label for="environment-approval-details">Reasons:</label>
<textarea class="span6" id="environment-approval-details"
name="approvalDetails.environmentApprovalDetails"
ng-maxlength="4000"
ng-required="model.approvalDetails.environmentApprovalsObtained === 'false'"
ng-model="model.approvalDetails.environmentApprovalDetails"></textarea>
</div>
</div>
</div>
</form>
</script>
<script type="text/ng-template" id="confirmation">
<form id="form" method="post" name="form" action="#" class="standard">
<div class="row">
<div class="span9">
<span class="checkbox inline">
<label for="confirm-information">
<input type="checkbox" id="confirm-information" name="confirmInformation"
ng-model="model.Confirmed" required />
I confirm that all the details are correct
</label>
</span>
</div>
</div>
</form>
</script>
<div class="form-actions">
<input type="button" class="btn" value="Cancel" ng-click="cancel()"/>
<div class="pull-right btn-toolbar">
<input id="previous" type="button" class="btn" value="Previous"
ng-click="workflow.handlePrevious()" ng-show="!workflow.isFirstStep()" ng-cloak/>
<input id="save-and-close" type="button" class="btn" value="Save draft and close"
ng-show="model.canSaveDraftAndClose && !workflow.isLastStep()"
ng-click="saveDraftAndClose()" ng-cloak/>
<input id="submit" type="button" class="btn btn-primary" value="{{workflow.getNextLabel()}}"
ng-disabled="!workflow.canNavigateToNextStep()"
ng-click="workflow.handleNext()" ng-cloak/>
</div>
</div>
</div>
Controllers:
angular.module('Test')
.config(function ($routeProvider) {
$routeProvider
.when('/applicant-details', {
templateUrl: 'applicant-details',
controller: 'ApplicantDetailsController'
})
.when('/methodology', {
templateUrl: 'methodology',
controller: 'MethodologyController'
})
.when('/approval-details', {
templateUrl: 'approval-details',
controller: 'ApprovalDetailsController'
})
.when('/confirmation', {
templateUrl: 'confirmation',
controller: 'ConfirmationController'
})
.otherwise({redirectTo: '/applicant-details'});
})
;
function LodgeApplicationWorkflowController( $scope, ctx, workflow, workflowModel, server, navigation) {
workflow.setSteps([
{
name: 'Applicant details',
path: 'applicant-details',
validationUrl: '/some url'
},
{
name: 'Methodology',
path: 'methodology'
},
{
name: 'Approval details',
path: 'approval-details'
},
{
name: 'Confirmation',
path: 'confirmation',
nextButtonLabel: 'Lodge',
onSubmit: function () {
disable('submit');
$scope.model.lodgeApplication = JSON.stringify($scope.model);
server.post({
url: ctx + '/some url' ,
json: JSON.stringify($scope.model),
successHandler: function () {
},
completeHandler: function () {
enable('submit');
},
validationErrorTitle: 'The request could not be completed because of the following issues:'
});
}
}
]);
function postInit() {
// To DO
}
function loadLodgement() {
// To DO
}
$scope.workflow = workflow;
$scope.model = workflowModel.model();
$scope.refData = workflowModel.refData();
$scope.accountDetails = {};
$scope.userDetails = {};
$scope.model.canSaveDraftAndClose = true;
server.getReferenceData([
'/URL1'
], function onAllReferenceDataRetrieved(data) {
$scope.$apply(function() {
$scope.refData.fuelSourceOptions = data[0];
$scope.refData.contactInfos = data[1].result;
$scope.refData.address = data[2];
$scope.refData.yearOptions = data[3];
$scope.refData.nmiNetworkOptions = data[4];
});
loadLodgement();
loadDraft();
});
$scope.saveDraftAndClose = function () {
var command = {};
server.post({
url: ctx + '/URL',
json: JSON.stringify(command),
successHandler: function (data) {
},
validationErrorTitle: 'The request could not be completed because of the following issues:'
});
};
$scope.cancel = function() {
navigation.to('Some URL');
};
}
function ApplicantDetailsController($scope, workflow, workflowModel, addressService, applicantServiceFactory) {
var applicantService = applicantServiceFactory();
if (!workflow.setCurrentScope($scope)) {
return;
}
$scope.model = workflowModel.model();
$scope.model.applicantDetails = _.extend({
owner: { address: {} },
operator: { address: {} }
}, $scope.model.applicantDetails);
addressService.initialiseAddress($scope.model.applicantDetails);
}
function MethodologyController($scope, workflow, workflowModel) {
if (!workflow.setCurrentScope($scope)) {
return;
}
$scope.model = workflowModel.model();
// Do something
}
function ApprovalDetailsController($scope, workflow, workflowModel) {
if (!workflow.setCurrentScope($scope)) {
return;
}
$scope.model = workflowModel.model();
$scope.model.approvalDetails = $scope.model.approvalDetails || {};
// Do something
}
function ConfirmationController($scope, workflow, workflowModel) {
if (!workflow.setCurrentScope($scope)) {
return;
}
$scope.model = workflowModel.model();
$scope.model.confirmation = { owner: {}, operator: {} };
$scope.model.confirmationConfirmed = false;
// Do something
}
WorkFlow
angular.module('Test')
.service('workflowModel', function() {
var refData = {};
var workflowModel = {};
return {
reset: function() {
workflowModel = {};
},
get : function(fragmentName) {
if (!workflowModel[fragmentName]) {
workflowModel[fragmentName] = {};
}
return workflowModel[fragmentName];
},
model : function(newWorkflowModel) {
if (newWorkflowModel) {
workflowModel = newWorkflowModel;
} else {
return workflowModel;
}
},
refData : function() {
return refData;
},
toJSON: function() {
return JSON.stringify(workflowModel);
}
};
})
.directive('workflowBreadcrumbs', function() {
return {
restrict: 'E',
template: '<ul class="breadcrumb">' +
'<li ng-class="{\'active\': workflow.currentStepPathIs(\'{{step.path}}\')}" ng-repeat="step in workflow.configuredSteps" ng-cloak>' +
'{{step.name}}<span ng-if="!workflow.visitedStep(step.path)">{{step.name}}</span><span class="divider" ng-if="!$last">/</span>' +
'</li>' +
'</ul>',
transclude: true
};
})
.factory('workflow', function ($rootScope, $location, server, validator, workflowModel, $timeout) {
function getStepByPath(configuredSteps, stepPath) {
return _.find(configuredSteps, function(step) { return step.path === stepPath; });
}
function validateServerSide(currentStep, callback) {
if (currentStep.validationUrl) {
server.post({
url: ctx + currentStep.validationUrl,
json : JSON.stringify(workflowModel.model()),
successHandler : function() {
$rootScope.$apply(function() {
callback();
});
}
});
} else {
callback();
}
}
function navigateNext(configuredSteps, currentStep) {
var currentStepIndex = _.indexOf(configuredSteps, currentStep);
navigateTo(configuredSteps[currentStepIndex + 1]);
}
function navigateTo(step) {
$location.path(step.path);
}
return {
setCurrentScope: function(scope) {
this.currentScope = scope;
this.firstStep = _.first(this.configuredSteps);
this.lastStep = _.last(this.configuredSteps);
this.currentStep = this.getCurrentStep();
if (!(this.currentStep === this.firstStep || this.hasEverVisitedSteps())) {
this.reset();
return false;
}
this.currentStep.visited = true;
hideErrorMessages();
this.focusOnFirstInputElementAndScrollToTop();
return true;
},
setSteps: function(steps) {
this.configuredSteps = steps;
},
focusOnFirstInputElementAndScrollToTop: function() {
$timeout(function() {
angular.element('select, input, textarea, button', '[ng-view]')
.filter(':visible')
.first()
.one('focus', scrollToTitle)
.focus();
scrollToTitle();
});
},
hasEverVisitedSteps: function() {
return _.find(this.configuredSteps, function(step) {
return step.visited;
}) !== undefined;
},
isFirstStep: function() {
return this.currentStep === this.firstStep;
},
isLastStep: function() {
return this.currentStep === this.lastStep;
},
currentStepPathIs: function(stepPath) {
return this.currentStep && stepPath === this.currentStep.path;
},
visitedStep: function(stepPath) {
return getStepByPath(this.configuredSteps, stepPath).visited;
},
getNextLabel: function() {
if (this.currentStep && this.currentStep.nextButtonLabel) {
return this.currentStep.nextButtonLabel;
}
return (this.isLastStep()) ? 'Submit' : 'Next';
},
handlePrevious: function() {
if (!this.isFirstStep()) {
var currentStepIndex = _.indexOf(this.configuredSteps, this.currentStep);
navigateTo(this.configuredSteps[currentStepIndex - 1]);
}
},
canNavigateToNextStep: function() {
return this.currentScope && (!this.currentScope.canSubmit || this.currentScope.canSubmit());
},
handleNext: function() {
var configuredSteps = this.configuredSteps;
var currentStep = this.currentStep;
if(this.isLastStep()) {
this.validateCurrentStep(this.currentStep.onSubmit);
} else {
this.validateCurrentStep(function() {
navigateNext(configuredSteps, currentStep);
});
}
},
validateCurrentStep: function(callback) {
var currentStep = this.currentStep;
if (this.currentScope.form) {
validator.validate(this.currentScope, function() {
validateServerSide(currentStep, callback);
});
} else {
validateServerSide(currentStep, callback);
}
},
getCurrentStep: function() {
return getStepByPath(this.configuredSteps, $location.path().substring(1));
},
reset: function() {
_.each(this.configuredSteps, function(step) { step.visited = false; });
this.firstStep.visited = true;
navigateTo(this.firstStep);
}
};
});

ion-slides, each overlap with ng-repeat

I'm real newbie in ionic, html, angular and java script. I have an app that take some JSON data and display it with ng-repeat.
But when I tried to switch to the next slide, it overlap. and I have an $interval that refresh JSON each 5 sec, it reset to the first slide also.
here html:
<ion-view title="home">
<ion-content ng-controller="temperatureCtrl">
<div ng-init="init()"></div>
<ion-slides options="options" slider="data.slider" >
<ion-slide-page ng-repeat="channel in channels">
<div class="list">
<h2><center>canal# {{channel.canal}}</center></h2>
<br/>
<center>
<button class="button button-stable" ng-click="switchChannel(channel, channel.canal)" ng-model="channel.status">
{{channel.status}}
</button>
</center>
<div class="list">
<label class="item item-input">
<input type="text" style="text-align:center;" placeholder="Channel name" ng-model="channel.name" ng-focus="stopRefresh()" ng-blur="restartRefresh()">
</label>
</div>
<h4><center>
<span class="Ainput" ><h3>{{channel.temperature}}ÂșC</h3></span>
</center></h4>
<h3><center>Setpoint= {{channel.setPoint}}</center></h3><br>
<div class="item range range-positive">
<i class="icon ion-minus-round"></i>
<input type="range" name="setpoint" min="5" max="30" step="0.5" value="33" ng-model="channel.setPoint" ng-focus="stopRefresh()" ng-blur="restartRefresh()">
<i class="icon ion-plus-round"></i>
</div>
<centrer>
<button class="button button-dark button-block padding " ng-click="channelsClk(channel, channel.setPoint)">ok</button>
</centrer>
<h3>
<span class="permRun">{{channel.permission}}</span>
</h3>
<h3>
<span class="AoutputChannel">{{channel.percentOut}}%</span>
</h3>
</ion-slide-page>
</ion-slides>
</ion-content>
and the controler:
main.controller("temperatureCtrl", ["$scope", "$interval", "ArduinoService", function($scope, $interval, service) {
var autoRefresh;
$scope.channels = [];
$scope.options = {
loop: false,
effect: 'fade',
speed: 500,
}
$scope.data = {};
$scope.$watch('data.slider', function(nv, ov) {
$scope.slider = $scope.data.slider;
})
function startRefresh(){
autoRefresh = $interval(function() {
updateAjax();
}, 5000);
}
function updateAjax() {
service.getChannels(function(err, result) {//get json data
if (err) {
return alert(err);
}
// puis les mets dans le scope
$scope.channels = result.channels;
})
};
$scope.init = function() { //on load page first get data
updateAjax();
startRefresh()
}
$scope.switchChannel = function($scope, channel) { // change name function
var switchCh = {canal : $scope.canal, status : $scope.status}
service.switchChannel(switchCh, function() {
});
updateAjax();
};
$scope.channelsClk = function($scope, channel) {
var chanObj = {setPoint : $scope.setPoint, name : $scope.name, canal : $scope.canal
};
service.putChannels(chanObj, function() {
});
}
$scope.stopRefresh = function() { //ng-mousedown
$interval.cancel(autoRefresh);
};
$scope.restartRefresh = function() {
startRefresh();
};
$scope.$on('$destroy', function() {
// Make sure that the interval is destroyed too
$scope.stopRefresh();
});
}]);
remove option fade solve the problem.
$scope.options = {
loop: false,
//effect: 'fade', /* <-- */
speed: 500,
}

Passing data from one page to another in angular js

How do I pass data from one page to another in angular js?
I have heard about using something as services but I am not sure how to use it!
Given below is the functionality I want to execute!
On page 1:
<div class="container" ng-controller="mycontrl">
<label for="singleSelect"> Select Date </label><br>
<select nAMe="singleSelect" ng-model="dateSelect">
<option value="2/01/2015">2nd Jan</option>
<option value="3/01/2015">3rd Jan</option>
</select>
<br>
Selected date = {{dateSelect}}
<br/><br/><br/>
<label for="singleSelect"> Select time </label><br>
<select nAMe="singleSelect" ng-model="timeSelect">
<option value="9/10">9AM-10AM</option>
<option value="10/11">10AM-11AM</option>
<option value="11/12">11AM-12PM</option>
<option value="12/13">12PM-1PM</option>
<option value="13/14">1PM-2PM</option>
</select>
<button ng-click="check()">Check!</button>
<br>
Selected Time = {{timeSelect}}
<br/><br/>
User selects time and date and that is used to make call to the db and results are stored in a variable array!
Page 1 controller:
var config= {
params: {
time: times,
date:dates
}
};
$http.get('/era',config).success(function(response) {
console.log("I got the data I requested");
$scope.therapist_list = response;
});
Now how do I send this variable $scope.therapist_list which is an array to next page which will be having a different controller and also if services is use how do define it in my application.js file
application.js:
var firstpage=angular.module('firstpage', []);
var secondpage=angular.module('secondpage', []);
To save the data that you want to transfer to another $scope or saved during the routing, you can use the services (Service). Since the service is a singleton, you can use it to store and share data.
Look at the example of jsfiddle.
var myApp = angular.module("myApp", []);
myApp.controller("ExampleOneController", function($scope, NewsService) {
$scope.news = NewsService.news;
});
myApp.controller("ExampleTwoController", function($scope,NewsService) {
$scope.news = NewsService.news;
});
myApp.service("NewsService", function() {
return {
news: [{theme:"This is one new"}, {theme:"This is two new"}, {theme:"This is three new"}]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="ExampleOneController">
<h2>
ExampleOneController
</h2>
<div ng-repeat="n in news">
<textarea ng-model="n.theme"></textarea>
</div>
</div>
<div ng-controller="ExampleTwoController">
<h2>
ExampleTwoController
</h2>
<div ng-repeat="n in news">
<div>{{n.theme}}</div>
</div>
</div>
</body>
UPDATED
Showing using variable in different controller jsfiddle.
var myApp = angular.module("myApp", []);
myApp.controller("ExampleOneController", function($scope, NewsService) {
$scope.newVar = {
val: ""
};
NewsService.newVar = $scope.newVar;
$scope.news = NewsService.news;
});
myApp.controller("ExampleTwoController", function($scope, NewsService) {
$scope.anotherVar = NewsService.newVar;
$scope.news = NewsService.news;
});
myApp.service("NewsService", function() {
return {
news: [{
theme: "This is one new"
}, {
theme: "This is two new"
}, {
theme: "This is three new"
}]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="ExampleOneController">
<h2>
ExampleOneController
</h2>
<div ng-repeat="n in news">
<textarea ng-model="n.theme"></textarea>
</div>
<input ng-model="newVar.val">
</div>
<div ng-controller="ExampleTwoController">
<h2>
ExampleTwoController
</h2>
<div ng-repeat="n in news">
<div>{{n.theme}}</div>
</div>
<pre>newVar from ExampleOneController {{anotherVar.val}}</pre>
</div>
</body>
OK,
you write a another module ewith factory service e.g.
angular
.module('dataApp')
.factory('dataService', factory);
factory.$inject = ['$http', '$rootScope', '$q', '$log'];
function factory($http, $rootScope,$q,$log) {
var service = {
list: getList
};
service.therapist_list = null;
return service;
function getList() {
var config= {
params: {
time: times,
date:dates
}
};
$http.get('/era',config).success(function(response) {
console.log("I got the data I requested");
$scope.therapist_list = response;
});
$log.debug("get Students service");
$http.get('/era',config).then(function successCallback(response) {
service.therapist_list = response.data;
$log.debug(response.data);
}, function errorCallback(response) {
$log.debug("error" + response);
});
}
}
Add this module as dependencies to your both page apps like
var firstpage=angular.module('firstpage', [dataApp]);
var secondpage=angular.module('secondpage', [dataApp]);
and then in your controller consume that service
.controller('homeController', ['$scope', 'dataService', function ($scope, dataService) {
}]);

How to query parse.com users through factory Service in AngularJS?

Building an cross-platform hybrid app using Parse.com, AngularJS using the Ionic Framework. The user creation and querying works fine when using the simple parse.com code from the docs.
However I have been trying to put the query into a AngularJS service, so that it can be accesses and I can do a ng-repeat to display the returned results in a list.
The code put in place so far is this:
View (search.html):
<div class="row">
<div class="col col-75">
<label class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" placeholder="Search" ng-model="search.queryvalue">
</label>
</div>
<div class="col">
<button class="button button-calm" ng-click="searchnow()">Search</button>
</div>
</div>
<ion-list>
<ion-item class="item-avatar" type="item-text-wrap" ng-repeat="user in users">
<img ng-src="{{userpic}}.png">
<h2>{{user.id}}</h2>
<p>{{user.get('location')}}</p>
</ion-item>
</ion-list>
Controller:
.controller('SearchCtrl', function($scope, $state, $rootScope, parseQueryFactory) {
$scope.search = {};
$scope.users = {};
$scope.searchnow = function () {
$scope.users = parseQueryFactory.searchUsers($scope.search.queryvalue);
};
})
Services:
.factory('parseQueryFactory', function($http) {
var query = new Parse.Query(Parse.User);
var people = {};
return {
searchUsers: function(searchVal){
query.startsWith("username", searchVal); // Search username
query.limit(20);
return query.find({
success: function(people) {
/*var objects = {};
for (var i = 0; i < people.length; i++) {
var object = people[i];
objects = objects + object;
}
console.log(people);
return objects;*/
},
error: function(error) {
return error;
}
});
}
}
})
I have tried a few ways to make this work (using sources like the ionic forum, stackoverflow and Google in general), but I am new to angular and not sure how to go about doing this.
The only thing that works is by putting the following code in the controller (but then I cannot use ng-repeat):
$scope.searchnow = function () {
var queryvalue = $scope.user.queryvalue;
userquery.startsWith("username", queryvalue); // Search username
userquery.limit(20);
userquery.find({
success: function(people) {
for (var i = 0; i < people.length; i++) {
var object = people[i];
console.log("ID: " + object.id + ', username: ' + object.get('username'));
}
}, error: function(error) {
console.log("error");
}
});
};
Has anyone implemented such a service for parse.com?
I have looked around and tried implementations from various people, but nothing seems to work in a way that returns a service like response from which ng-repeat comands can be done.
I believe this might help.
Services:
app.factory('Presentation', function($q) {
var Presentation = Parse.Object.extend(Parse.User, {
// Instance methods
}, {
// Class methods
listByUser : function() {
var defer = $q.defer();
var query = new Parse.Query(this);
query.startsWith("username", searchVal); // Search username
query.limit(20);
query.find({
success : function(aPresentations) {
defer.resolve(aPresentations);
},
error : function(aError) {
defer.reject(aError);
}
});
return defer.promise;
}
});
// Properties
Presentation.prototype.__defineGetter__("location", function() {
return this.get("location");
});
Presentation.prototype.__defineGetter__("pic", function() {
var pic = this.get("pic");
if (pic ==null){
pic = 'img/default.png';
return pic;
}
return pic.url();
});
return Presentation; });
Controller:
app.controller('userController', function( Presentation){
user = this;
Presentation.listByUser().then(function(aPresentations) {
user.list = aPresentations;
}, function(aError) {
// Something went wrong, handle the error
});
});
html:
<div class="row">
<div class="col col-75">
<label class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" placeholder="Search" ng-model="search.queryvalue">
</label>
</div>
<div class="col">
<button class="button button-calm" ng- click="searchnow()">Search</button>
</div>
</div>
<ion-list>
<ion-item class="item-avatar" type="item-text-wrap" ng-repeat="user in users">
<img ng-src="{{user.pic}}">
<h2>{{user.id}}</h2>
<p>{{user.location}}</p>
</ion-item>
</ion-list>
For further reading you can check out 5 Tips for using parse with angularjs by slidebean.

AngularJS doesn't bind ng-model to scope

I have the following code for my search function
<ion-content class="has-header" id="content" push-search>
<div id="search-bar">
<div class="item item-input-inset">
<label class="item-input-wrapper" id="search-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" placeholder="Search" ng-model="query" ng-change="search()">
</label>
</div>
</div>
<div>
<// code for displaying search results//>
</ion-content>
Search Controller
.controller('SearchCtrl', function($scope, SearchFactory) {
var doSearch = ionic.debounce(function(query) {
console.log($scope);
$scope.results = SearchFactory.get({'query':$scope.query});
}, 500);
$scope.search = function() {
doSearch($scope.query);
}
})
Search Factory:
.factory('SearchFactory', function($resource) {
return $resource(url.concat('/paths/search/:query'),
{query: '#query' } ,
{ get: { method: 'GET' , isArray: true} }
);
})
When I do call Search, there is no $scope.query in my $scope:
(see) http://i.stack.imgur.com/MuxRt.png
It was solved. See this Link for more info http://jimhoskins.com/2012/12/14/nested-scopes-in-angularjs.html
Short answer is that the "query" needs to be a field in a scope search object so that it is passed by reference rather than by value, eg:
.controller('SearchCtrl', function($scope, SearchFactory) {
$scope.searchParams = {};
$scope.searchParams.query = '';
var doSearch = ionic.debounce(function(query) {
console.log($scope);
$scope.results =SearchFactory.get({'query':$scope.searchParams.query});
}, 500);

Resources