In Angular ui calendar showing the date properly but it not showing the time in event scheduler.In browser there is no error on console but time not showing.How can i get time on calendar
angular js file:
dashboard.controller("ReservationController", ['$rootScope', '$scope', '$state', '$location','$http', 'dashboardService', 'Flash',
function ($rootScope, $scope, $state, $location, $http, dashboardService, Flash) {
var vm = this;
vm.reservation = {};
console.log("Reservation");
}]).factory('mmUrl', function($http)
{
return $http.get("Youin-api/v2/business/44/view_reservation");
}).controller('CalendarCtrl',
function($scope, $rootScope, ngDialog, $compile, $timeout, uiCalendarConfig, $location,$http, dashboardService, Flash,mmUrl) {
CalendarCtrl = {};
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var evnt = [];
$scope.events=[];
$scope.changeTo = 'Hungarian';
/* event source that calls a function on every view switch */
$scope.eventsF = function (start, end, timezone, callback)
{
var events ;
$scope.events=[];
mmUrl.success(function(data){
$scope.events = angular.fromJson(data.reservation_list);
callback($scope.events);
});
};
$scope.alertOnEventClick = function( date, jsEvent, view){
var event_id=date.id;
$http.post("Youin-api/v2/business/event_information",{event_id:event_id}).then(function(response) {
if(response.data.error="false")
{
console.log(response.data);
document.getElementById("title").value = response.data.title;
document.getElementById("amount").value = response.data.amount;
document.getElementById("deal_id").value = response.data.deal_id;
$('#EventInfo').modal('show');
}
});
};
$scope.changeView = function(view,calendar) {
uiCalendarConfig.calendars[calendar].fullCalendar('changeView',view);
};
$scope.renderCalender = function(calendar) {
$timeout(function() {
if(uiCalendarConfig.calendars[calendar]){
uiCalendarConfig.calendars[calendar].fullCalendar('render');
}
});
};
$scope.eventRender = function( event, element, view ) {
element.attr({'tooltip': event.title,
'tooltip-append-to-body': true});
$compile(element)($scope);
};
$scope.uiConfig = {
calendar:{
height: 450,
editable: false,
allDay: false,
ignoreTimezone: false,
header:{
left: 'title',
center: 'month',
right: 'today prev,next'
},
eventClick: $scope.alertOnEventClick,
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize,
eventRender: $scope.eventRender
}
};
$scope.eventSources = [$scope.events,$scope.eventsF];
$scope.eventSources2 = [$scope.events,$scope.eventsF];
});
My front end:
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 padding-right-5 padding-left-5" ng-controller="CalendarCtrl">
<div class="" align="left">
<div class="tab-wrap">
<input type="radio" name="tabs" id="tab1" checked ng-click="changeView('month', 'myCalendar3')" >
<div class="tab-label-content" id="tab1-content">
<label for="tab1" class="label1">Monthly View</label>
<div class="tab-content mdl-shadow--4dp">
<div class="calendar" ng-model="eventSources2" calendar="myCalendar3" ui-calendar="uiConfig.calendar"></div>
</div>
</div>
<div class="alert-success calAlert" ng-show="alertMessage != undefined && alertMessage != ''">
<h4>{{alertMessage}}</h4>
</div>
<input type="radio" name="tabs" id="tab2" ng-click="changeView('agendaDay', 'myCalendar3')">
<div class="tab-label-content" id="tab2-content">
<label for="tab2" class="label1">Daily View</label>
<div class="tab-content mdl-shadow--4dp">
<div class="calendar" ng-model="eventSources" calendar="myCalendar3" ui-calendar="uiConfig.calendar"></div>
</div>
</div>
<div class="slide"></div>
</div>
</div>
thanks in advance..!!
Related
This is The Data in the sql db
and this is the AngulaJJ Ui-Calendar
The Problem is: the data in the db presented with another values in the UI
'use strict';
app.controller('eventController', ['$scope', 'uiCalendarConfig', '$http', 'ngAuthSettings', function ($scope, uiCalendarConfig, $http, ngAuthSettings) {
var serviceBase = ngAuthSettings.apiServiceBaseUri;
$scope.SelectedEvent = null;
var isFirstTime = true;
$scope.events = [];
$scope.eventSources = [$scope.events];
//get the events data from server
$http.get(serviceBase + 'api/Event/GetEvents', {
cache: true,
params: {}
}).then(function (data) {
//get and push events data to calendar here
console.log(data.data);
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function (value) {
$scope.events.push({
title: value.EventTitle,
description: value.EventDescription,
start:parseInt(value.StartDate),
end: parseInt(value.EndDate),
allDay: value.IsFullDay,
stick: true
});
});
});
//Calender configration in angular
$scope.uiConfig = {
calendar: {
height: 700,
editable: true,
displayEventTime: false,
header: {
left: 'month basicWeek basicDay agendaWeek agendaDay',
center: 'title',
right: 'today prev,next'
},
eventClick: function (event) {
$scope.SelectedEvent = event;
},
eventAfterAllRender: function () {
if ($scope.events.length > 0 && isFirstTime) {
//Focus first event
uiCalendarConfig.calendars.myCalendar.fullCalendar('gotoDate', $scope.events[0].start);
isFirstTime = false;
}
}
}
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<h1 class="form-login-heading">Calendar</h1>
<div ng-controller="eventController">
<div class="row">
<div class="col-md-12 col-lg-12">
<div id="calendar" ui-calendar="uiConfig.calendar" class="bold blue" ng-model="eventSources" calendar="myCalendar"></div>
</div>
<div class="row col-md-4 text-center center">
<div ng-show="SelectedEvent" class="alert alert-success" style="margin-top:50px">
<h2 style="margin-top:0px"> Selected Event:</h2>
<h3 style="color:#A9A50E">{{SelectedEvent.title}}</h3>
<p>{{SelectedEvent.description}}</p>
</div>
</div>
</div>
</div>
I used:
start: new Date(parseInt(value.StartDate)) > Not Working
and also used:
the data type in the db of this col > DateTime , Date , nvarchar. > Not Working and Same Error.
To sum up:
The problem is: in db the date = 2018-09-09 but in the Ui-view( using angularJS) date = 1-1-1970.
I need to know where is the problem, and how to solve it
The date you have received from service is in string format you need to convert it to javascript date object.
so in your case you can do it as follows
start: new Date(value.StartDate)
i am using angular ui-calendar for displaying a series of leaves.The data for this is fed from the REST services.I can add a leave to the database also.The problem is that when i add a leave detail to the database it does not automatically reflect in the calendar.If i refresh the page the data will be reflected. Basically what I want to do is when I submit the form (closing the modal) the data to be displayed in the calendar. Thank you in advance.Following is my code
My controller
app.factory('calendarSer', ['$http', '$rootScope', 'uiCalendarConfig', function($http, $rootScope, uiCalendarConfig) {
return {
displayCalendar: function($scope) {
$http.get("rest/leave/holidayList", {}).success(function(data, status, headers, config) {
$scope.holidayList = data;
$calendar = $('[ui-calendar]');
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
$scope.changeView = function(view) {
$calendar.fullCalendar('changeView', view);
};
var m = null;
if ($scope.selectable == "Yes") {
m = true;
} else {
m = false;
}
/* config object */
$scope.uiConfig = {
calendar: {
lang: 'da',
height: 400,
editable: true,
selectable: m,
header: {
left: 'month basicWeek basicDay',
center: 'title',
right: 'today prev,next'
},
eventClick: function(date, jsEvent, view) {
$scope.alertMessage = (date.title + ' was clicked ');
alert("clicked" + date.title);
},
select: function(start, end, allDay) {
var obj = {};
obj.startDate = start.toDate();
obj.endDate = moment(end - 1 * 24 * 3600 * 1000).format('YYYY-MM-DD');
$rootScope.selectionDate = obj;
$("#modal1").openModal();
// calendar.fullCalendar('unselect');
},
dayRender: function(date, cell) {
var today = new Date();
today = moment(today).toDate();
var end = new Date();
end = moment(end).toDate();
end.setDate(today.getDate() + 7);
date = moment(date).toDate();
angular.forEach($scope.holidayList, function(value) {
if (((moment(value.holiday_date).format("YYYY-MM-DD")) == moment(date).format("YYYY-MM-DD"))) {
cell.css("background-color", "#2bbbad");
//$('.date').text('Today');
cell.prepend("<span style=\"max-width:200px;word-wrap:break-word;margin-top:10px;\">" + value.description + "</span>");
cell.prepend("<br>")
}
});
},
eventRender: $scope.eventRender,
}
};
console.log($scope.holidayList);
}).error(function(data, status, headers, config) {
alert("error from holidaylist");
});
$scope.events = [];
$scope.eventSources = [$scope.events];
$http.get($scope.url, {
cache: true,
params: {}
}).then(function(data) {
console.log(data);
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function(value) {
console.log(value.title);
if (value.approvalStatus == "Approved") {
var k = '#114727';
} else {
k = '#b20000'
}
$scope.events.push({
title: value.signum,
description: value.signum,
start: value.startDate,
end: value.endDate,
allDay: value.isHalfDay,
stick: true,
status: value.approvalStatus,
backgroundColor: k
});
});
});
}
}
}]);
g-include
<div id="controllerid">
<div class="row" >
<div class="col s10 m10 l10">
<div id="calendar" ui-calendar="uiConfig.calendar" ng-model="eventSources" calendar="myCalendar"></div>
</div>
</div>
<!-- Modal Structure -->
<div id="modal1" class="modal" ng-controller="MyAddController">
<div class="modal-content">
<h4>Apply Leave</h4>
<div class="row">
<form class="col s12" id="form1">
<div class="row modal-form-row">
<div class="input-field col s6">
<input id="num" type="text" class="validate" ng-model="test.num"> <label for="num">num</label>
</div>
<div class="input-field col s6">
<input id="ename" type="text" class="validate" ng-model="test.title"> <label for="ename">Employee Name</label>
</div>
</div>
<div class="row">
<form class="col s12">
<div class="row modal-form-row">
<div class="input-field col s5">
<input id="startDate" type="text" class="validate" value="{{selectionDate.startDate | date}}" readonly >
</div>
<div class="input-field col s5">
<input id="endDate" type="text" class="validate" value="{{selectionDate.endDate | date}}" readonly>
</div>
<div class="input-field col s1">
<p>
<input type="checkbox" id="test6" ng-model="test.isHalfDay" /> <label for="test6">Half Day</label>
</p>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="description" type="text" class="validate" ng-model="test.description"> <label for="description">Description</label>
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button class="btn waves-effect waves-light" type="submit" ng-click="add()" name="action"> Submit <i class="material-icons right">send</i>
</button>
</div>
</div>
and my add controller
app.controller("MyAddController", function($scope, $http,$rootScope,calendarSer) {
$scope.test = {};
$scope.add = function() {
$("#modal1").closeModal();
$scope.test1=$rootScope.selectionDate;
var jsonData = JSON.stringify($.extend({}, $scope.test, $scope.test1));
console.log(""+jsonData);
$http({
url: "rest/leave/create",
method: "POST",
data: jsonData,
headers: {'Content-Type': 'application/json'}
}).success(function(data, status, headers, config) {
if (data) {
console.log("Entered in the add controller");
$scope.data = data;
$scope.url="rest/leave/list";
$scope.selectable="Yes";
calendarSer.displayCalendar($scope);
$("#popupmodal").openModal();
console.log("Exited in the add controller");
}
}).error(function(data, status, headers, config) {
alert("error from create leave");
})
}
});
ANy help would be appreciated
In your "success" function after you run the "create" function, you can simply add the event to fullCalendar using the same data, via the built-in "renderEvent" function.
Something like this (I don't know Angular, so you may need to adjust this slightly to get your calendar element into context, but hopefully you understand the idea). I am also assuming that jsonData contains all the relevant event data which we can use for this:
.success(function(data, status, headers, config) {
if (data) {
console.log("Entered in the add controller");
$scope.data = data;
//add the event to the calendar UI without refreshing the events
$('[ui-calendar]').fullCalendar("renderEvent",
{
start: jsonData.startDate,
end: jsonData.endDate,
title: jsonData.title
},
true //make it stick even when the view changes
);
$scope.url="rest/leave/list";
$scope.selectable="Yes";
calendarSer.displayCalendar($scope);
$("#popupmodal").openModal();
console.log("Exited in the add controller");
}
You may need to add more fields, or you may need to get momentJS to parse the values in startDate / endDate, depending exactly what those fields output.
The "renderEvent" method can be found in the fullCalendar documentation here: https://fullcalendar.io/docs/event_rendering/renderEvent/
what i m doing:
simple html file shows first page , in this page i have one title and button, initially i set $scope.index = 0. so, we set first position of array. when we click on next button it finds firstCtrl and first.html page. in this controller i update $scope.index by 1. so, my question is when i update $scope.index of myCtrl then $scope.index is changed on another controller i wants to change myCtrl. is it possible ? if it is then help me.
index.html:
<body ng-controller="myCtrl">
<div id="navbar">
<div class="setToggle">
<input id="slide-sidebar" type="checkbox" role="button" />
<label for="slide-sidebar"><span class="glyphicon glyphicon-menu-hamburger"></span></label>
</div>
<div class="setQuestion">
<h2>{{surveys[index].questionTitle}}</h2>
</div>
</div>
<div class="content-wrapper" class="container-fluid">
<div class="sidebar-left">
<div class="first">
<ul ng-repeat="cat in surveys[index].category" class="list-unstyled" ng-hide="checkSubCategoryValueIsNull.length">
<li class="category">
<a ng-click="expand=!expand">
<span class="glyphicon" ng-class="{'glyphicon-plus': !expand, 'glyphicon-minus': expand}">
{{cat.categoryName}}
</span>
</a>
</li>
<ul ng-repeat="subcategory in cat.categoryItemDto" class="list-unstyled">
<li ng-show="expand">
<label class="label-style-change">
<input type="checkbox" ng-click="toggleSelectionCheckbox(surveys[index], subcategory)" ng-model="subcategory.selectValue" ng-disabled="disableCheckbox">
<span class="subcategory-item" ng-disabled="disableCheckbox">{{subcategory.subCategoryName}}</span>
</label>
</li>
</ul>
</ul>
</div>
<div class="second">
<input type="button" name="Submit" value="Submit" ng-click="submitSelection()" ng-hide="hideSubmitButton" ng-disabled="!selections[index].length">
<input type="button" name="Edit" value="Edit" ng-click="EditSelection()" ng-show="hideEditButton">
</div>
</div>
<div class="portfolio">
<div id="main">
<div ng-view></div>
</div>
</div>
</div>
</body>
controller.js
(function() {
var app = angular.module("app.controllers", ["app.service"]);
app.controller("myCtrl", ["$scope", "$http", "$location", "$timeout", "surveyService", "Data",
function ($scope, $http, $location, $timeout, surveyService, Data) {
surveyService.getData(function(dataResponse) {
$scope.surveys = dataResponse;
$scope.selections = [];
/* create 2d array mannually */
var numInternalArrays = $scope.surveys.length;
for (var i = 0; i < numInternalArrays; i++) {
$scope.selections[i] = [];
};
$scope.index = 0;
var toggleCheckboxFlag = 0;
/* PRIVATE FUNCTION
for find value from selections array and replace it
*/
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
array.splice(index, 1);
toggleCheckboxFlag = 1;
}
});
}
$scope.toggleSelectionCheckbox = function (QuestionId, value) {
toggleCheckboxFlag = 0;
if (!value) return;
findAndRemove($scope.selections[$scope.index], 'categoryId', value.subCategoryId);
if (toggleCheckboxFlag != 1) {
$scope.selections[$scope.index].push({
questionId: QuestionId.questionId,
categoryId: value.subCategoryId,
categoryName: value.subCategoryName,
storeId: 1,
comment: ""
});
}
};
$scope.submitSelection = function() {
$scope.value = $scope.selections[$scope.index];
$scope.hideSubmitButton = true;
$scope.disableCheckbox = true;
$scope.hideEditButton = true;
$location.path("/question/1");
}
});
$scope.EditSelection = function() {
$scope.hideEditButton = false;
$scope.hideSubmitButton = false;
$scope.disableCheckbox = false;
$scope.value = false;
}
$scope.$watch('index', function (newValue, oldValue) {
if (newValue !== oldValue) Data.setIndex(newValue);
});
console.log("controller", Data.getIndex())
}]);
})();
app.js
var app = angular.module('app', ['ngRoute','app.service', 'app.controllers']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/question/1', {
templateUrl: 'views/first.html',
controller: 'sidebarCtrl'
})
.when('/question/2', {
templateUrl: 'views/second.html',
controller: 'mainCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
first.html
<div id="content-wrapper" ng-show="value">
<div class="col-lg-offset-1 col-lg-8 col-md-12 col-sm-12 col-xs-12">
<h2 class="subCategoryLabel"><span class="label">{{value[inc].categoryName}}</span></h2>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<button class="btnNext" ng-hide="inc == 0" ng-click="prev()">
<i class="glyphicon glyphicon-menu-left"></i>
</button>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<form name="myForm">
<div ng-repeat="item in surveys[index].optionCategoryItemDto" class="formStyle">
<label class="text-center">
<input type="radio" name="radio" id="{{item.itemId}}" ng-value="item.itemId" ng-model="selections[index][inc].answer" required>
{{item.itemName}}
</label>
</div>
<br/>
<br/>
</form>
</div>
<div class="col-lg-3 col-lg-offset-1 col-md-offset-1 col-md-3 col-sm-4 col-xs-4">
<button class="btnNext" ng-hide="selections[index].length == inc + 1" ng-disabled="myForm.radio.$error.required" ng-click="next()">
<i class="glyphicon glyphicon-menu-right"></i>
</button>
<button class="btnNext" ng-show="selections[index].length == inc + 1" ng-disabled="myForm.radio.$error.required" ng-click="nextQuestion()">
<i class="glyphicon glyphicon-forward"></i>
</button>
</div>
</div>
<div class="col-lg-offset-3 col-lg-4 col-md-offset-3 col-md-6 col-sm-offset-3 col-sm-6 col-xs-4">
<textarea type="text" id="text" class="form-control txtArea" ng-model="selections[index][inc].comment" placeholder="Write comment..."></textarea>
</div>
</div>
sidebarCtrl.js
in this controller i update $scope.index when we call nextQuestion(). here $scope.index increment by one and $watch function also get latest value of index. but myCtrl is not update. i wants to update myCtrl.
(function() {
var app = angular.module("app.controllers");
app.controller("sidebarCtrl", ['$scope', "$location", "Data", function($scope, $location, Data) {
$scope.inc = 0;
$scope.next = function() {
$scope.inc += 1;
}
$scope.prev = function() {
$scope.inc -= 1;
}
$scope.nextQuestion = function() {
$scope.index += 1;
$location.path("/question/2");
}
$scope.$watch('index', function (newValue, oldValue) {
console.log("SASAS", newValue)
if (newValue !== oldValue) Data.setIndex(newValue);
});
}]);
})();
service.js
(function() {
var app = angular.module("app.service", []);
app.service("surveyService", function($http) {
this.getData = function (callbackFunc) {
$http({
method: "GET",
data: {something: true},
contentType: 'application/json',
dataType: 'jsonp',
url: "http://localhost:8080/TheSanshaWorld/sfcms/fetch-survey-details"
}).success(function(data){
callbackFunc(data);
}).error(function(){
alert("error");
});
};
this.setData = function(value) {
if (confirm('Do you wanna to submit?')) {
$http.post("http://localhost:8080/TheSanshaWorld/sfcms/save-survey-result-data", value).success(function(data, status) {
window.open("../index.html","_self");
});
} else {
return false;
}
};
});
app.factory('Data', function () {
var data = {
Index: ''
};
return {
getIndex: function () {
return data.Index;
},
setIndex: function (index) {
data.Index = index;
console.log("service", data.Index)
}
};
});
})();
Because sidebarCtrl is nested within myCtrl, therefore you can reach myCtrl $scope.index from sidebarCtrl using it $scope.$parent.index,
Try it by test: add any parameter value to myCtrl $scope.name='Bob';
then log it in sidebarCtrl console.log($scope.$parent.name); you should see printed 'Bob'. Do the same with index.
I am trying to bind data between a service, controller and a view. Below, I have provided plunker link for the app.
Basically 'dataService' has a function to find geolocation. The function sets the variable dataService.locationDone.
The dataService is assigned to $scope.data in the 'HomeController'.
In home.html, I refer the value of data.locationDone to show different labels.
The issue is, after the locationDone variable is modified in the dataService, the labels in the home.html does not change.
plunker link: http://embed.plnkr.co/BomSztgC7PzGMzJyDKoF/preview
Service:
storelocator.factory('dataService', [function() {
var data = {
locationDone: 0,
position: null,
option: null
}
var getLocation = function() {
data.locationDone = 0;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (pos) {
data.locationDone = 1;
data.position = pos;
console.log('got location ', data.locationDone);
}, function () {
data.locationDone = 2;
});
} else {
data.locationDone = 3;
}
};
getLocation();
return data;
}]);
Controller:
storelocator.controller('HomeController', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {
$scope.data = dataService;
console.log('Home ctrl', $scope.data.locationDone);
$scope.fn = {};
$scope.fn.showOne = function () {
$scope.data.option = 3;
$location.path('/map');
};
$scope.fn.showAll = function () {
$scope.data.option = 99;
$location.path('/map');
};
}]);
view:
<div layout="column" layout-align="start center">
<div layout="column" layout-margin layout-padding>
<div flex layout layout-margin layout-padding>
<md-whiteframe flex class="md-whiteframe-z1" layout layout-align="center center" ng-show="data.locationDone==0">
<span flex>Awaiting location information.</span>
</md-whiteframe>
<md-whiteframe flex class="md-whiteframe-z1" layout layout-align="center center" ng-show="data.locationDone==2"><span flex>Error in getting location.</span>
</md-whiteframe>
<md-whiteframe flex class="md-whiteframe-z1" layout layout-align="center center" ng-show="data.locationDone==3"><span flex>The browser does not support location.</span>
</md-whiteframe>
</div>
<md-button flex ng-show="data.locationDone==1" class="md-accent md-default-theme md-raised" ng-click="fn.showOne()">Find Nearest Three Stores</md-button>
<div flex></div>
<md-button ng-show="data.locationDone==1" flex class="md-accent md-default-theme md-raised" ng-click="fn.showAll()">Find All Stores</md-button>
</div>
</div>
You are updating the variable locationDone defined in the scope of the service. It will not have any impact on the object that you have returned during in the service (when updated later). Instead predefine an object in your service and update the property on the reference rather than a variable.
Also note that since you are using native async api, which runs out of the angular context you would need to manually invoke digest cycle by doing $rootScope.$apply() in your case or just use $timeout wrap your updates in $timeout. However better approach would be to property create an api in dataService with method returning $q promise.
With timeout
.factory('dataService', ['$timeout', function($timeout) {
var service = { //Define here;
locationDone: 0,
position: null,
option: null
}
var getLocation = function() {
service.locationDone = 0;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (pos) {
$timeout(function(){
service.locationDone = 1;
service.position = pos;
});
}, function () {
$timeout(function(){
service.locationDone = 2;
});
});
} else {
service.locationDone = 3;
}
};
getLocation();
return service; //return it
}]);
With qpromise implementation:
.factory('dataService', ['$q', function($q) {
return {
getLocation:getLocation
};
function getLocation() {
if (navigator.geolocation) {
var defer = $q.defer();
navigator.geolocation.getCurrentPosition(function (pos) {
defer.resolve({locationDone : 1,position : pos})
}, function () {
defer.resolve({ locationDone : 2});
});
return defer.promise;
}
return $q.when({locationDone : 3});
};
}]);
And in your controller:
$scope.data = {};
dataService.getLocation().then(function(result){
$scope.data = result;
});
Demo
angular.module('app', []).controller('HomeController', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {
$scope.data = {};
dataService.getLocation().then(function(result){
$scope.data = result;
})
console.log('Home ctrl', $scope.data.locationDone);
$scope.fn = {};
$scope.fn.showOne = function () {
$scope.data.option = 3;
$location.path('/map');
};
$scope.fn.showAll = function () {
$scope.data.option = 99;
$location.path('/map');
};
}]).factory('dataService', ['$q', function($q) {
return {
getLocation:getLocation
};
function getLocation() {
if (navigator.geolocation) {
var defer = $q.defer();
navigator.geolocation.getCurrentPosition(function (pos) {
defer.resolve({locationDone : 1,position : pos})
}, function () {
defer.resolve({ locationDone : 2});
});
return defer.promise;
}
return $q.when({locationDone : 3});
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="HomeController">
<div layout="column" layout-align="start center">
<div layout="column" layout-margin layout-padding>
<div flex layout layout-margin layout-padding>
<md-whiteframe flex class="md-whiteframe-z1" layout layout-align="center center" ng-show="data.locationDone==0">
<span flex>Awaiting location information.</span>
</md-whiteframe>
<md-whiteframe flex class="md-whiteframe-z1" layout layout-align="center center" ng-show="data.locationDone==2"><span flex>Error in getting location.</span>
</md-whiteframe>
<md-whiteframe flex class="md-whiteframe-z1" layout layout-align="center center" ng-show="data.locationDone==3"><span flex>The browser does not support location.</span>
</md-whiteframe>
</div>
<md-button flex ng-show="data.locationDone==1" class="md-accent md-default-theme md-raised" ng-click="fn.showOne()">Find Nearest Three Stores</md-button>
<div flex></div>
<md-button ng-show="data.locationDone==1" flex class="md-accent md-default-theme md-raised" ng-click="fn.showAll()">Find All Stores</md-button>
</div>
</div>
</div>
Im trying to send data from user input to display on the screen when button click.
The problem is that if i click on the button it simply passes to the next value without gathering the information and displaying in the screen. If i press ENTER it works how it should. i have searched all over internet several examples but simply couldnt get it to work. im using at the moment :
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
full html:
<div class="boxContent col-md-12">
<h1>{{lang.sec101.h1}}</h1>
<div class="col-md-12 lineBorder noPad" >
<div class="box1">
<p>
{{lang.sec101.title}}
</p>
</div>
<!-- dynamic form -->
<div class="col-md-12 borderBox boxLeft bg_box">
<form novalidate name="addForm">
<div class="boxLeft" ng-show="Question != ''">
<div ng-show="Question.infotip != 'yes'">
<h1 class="heading_left">{{Question.ask}}</h1>
</div>
<div ng-show="Question.infotip == 'yes'">
<h1 class="heading_left info">{{Question.ask}}
<span class="infotip yourData" tooltip-placement="top" tooltip-trigger="click" tooltip="{{Question.infotipText}}"></span>
</h1>
</div>
</div>
<div class="boxRight" ng-show="Question != ''">
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
</div>
<div class="boxRejestracjaInput">
<!-- <div id="legg-select" ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</div> -->
<div class="newSelect">
<label ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</label>
</div>
<input
ng-if="Question.type === 'text'"
type="{{Question.type}}"
name="institutionName"
class="inputName"
value="{{Question.value}}"
ng-model="value"
ng-minlength="{{Question.min}}"
ng-maxlength="{{Question.max}}"
ng-keypress="enter($event,value)"
placeholder="{{Question.placeholder}}"
ng-pattern="{{Question.pattern}}" />
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.minlength || addForm.institutionName.$error.maxlength">
Minimum {{Question.min}} znaków
</div> -->
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.maxlength">
Max {{Question.max}} znaków
</div> -->
<div class="custom-error institution" ng-show="addForm.institutionName.$error.pattern || addForm.institutionName.$error.maxlength || addForm.institutionName.$error.minlength">
{{Question.copy}}
</div>
</div>
</form>
</div>
<p>
{{lang.sec101.title2}}
</p>
<a href="rejestracja_10edit.html" class="btn btn-lg btn-default bt_edit" type="button">
{{lang.sec101.title3}}<span class="btn_bg_img"></span>
</a>
</div>
<div class="col-md-12 noPad" ng-repeat="sek in formOut">
<h3 class="daneHeading">{{sek.name}}</h3>
<div class="row">
<div class="col-md-12" >
<div class="col-md-4 col-sm-6 boxContent3 boxes" ng-repeat="row in sek.data">
<span class="leftBoxContrnt">{{row.shortAsk}}</h4></span>
<h4 class="rightBoxContrnt">{{row.value}}</h4>
</div>
</div>
</div>
</div>
<!-- <div class="row col-md-12" >
<h3 class="daneHeading">Hasło</h3>
</div>
<div class="row">
<div class="col-md-12 " >
<div class="col-md-4 col-sm-6 boxContent3">
<span class="leftBoxContrnt">Test</h4></span><span class="blueTxt"> *</span>
<h4 class="rightBoxContrnt">Test</h4>
</div>
</div>
</div> -->
</div>
my controller:
var app = angular.module('app', ['ngAnimate', 'ngCookies', 'ui.bootstrap', 'ngSanitize', 'nya.bootstrap.select', 'jackrabbitsgroup.angular-slider-directive']);
// var rej10_Controller = function($scope, $http, $cookieStore, $timeout, limitToFilter) {
app.controller('rej10_Controller', ['$scope', '$http', '$cookieStore', '$sce', '$timeout', 'limitToFilter',
function($scope, $http, $cookieStore, $sce, $timeout, limitToFilter) {
var view = 10,
arr,
data,
counterSection = 0,
counterAsk = 0;
$scope.opts = {};
$scope.slider_id = 'my-slider';
$scope.opts = {
'num_handles': 1,
'user_values': [0, 1],
'slider_min': 0,
'slider_max': 1,
'precision': 0,
};
/* language */
if (!$cookieStore.get('lang'))
$cookieStore.put('lang', 'pl');
var lang = $cookieStore.get('lang');
$scope.language = lang;
$scope.setLang = function(data) {
$cookieStore.put('lang', data);
$http.get('../widoki/json/lang/' + data + '/rej_' + view + '.json').
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn.sekcja[counterSection].data[counterAsk];
console.log($scope.lang);
}).
error(function(data, status, headers, config) {
console.log('error load json');
});
$scope.language = data;
};
/* get language pack */
$http({
method: 'GET',
url: '../widoki/json/lang/' + lang + '/rej_' + view + '.json'
}).
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
$scope.langLen = $scope.lang.formIn.length;
}).error(function(data, status, headers, config) {
console.log('error load json');
});
/* dynamic form */
$scope.enter = function(ev, d) {
if (ev.which == 13) {
$scope.addData(d);
}
};
$scope.addData = function(data) {
var newData = {};
/* latamy po id sekcji i po id pytania */
if (!$scope.formOut) {
$scope.formOut = [];
}
/* budowanie modelu danych wychodzcych */
newData = {
sekcja: counterSection,
name: $scope.lang.formIn[counterSection].name,
data: []
};
console.log(name);
if (!$scope.formOut[counterSection]) {
$scope.formOut.push(newData);
}
$scope.formOut[counterSection].data.push($scope.Question);
$scope.formOut[counterSection].data[counterAsk].value = data;
counterAsk++;
// zmieniamy sekcje
if (counterAsk == $scope.lang.formIn[counterSection].data.length) {
counterAsk = 0;
counterSection++;
}
if (counterSection == $scope.lang.formIn.length) {
$scope.Question = '';
/* zrobic ukrycie pola z formularza */
} else {
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
}
/* konwertowanie do jsona */
//var Json = angular.toJson($scope.formOut);
//console.log(Json);
};
$scope.submit = function() {
alert('form sent'); /* wysĹanie formularza */
};
$scope.getClass = function(b) {
return b.toString();
};
}
]);
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
app.config(['$tooltipProvider',
function($tooltipProvider) {
$tooltipProvider.setTriggers({
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur',
'never': 'mouseleave',
'show': 'hide'
});
}
]);
var ValidSubmit = ['$parse',
function($parse) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, element, iAttrs, controller) {
var form = element.controller('form');
form.$submitted = false;
var fn = $parse(iAttrs.validSubmit);
element.on('submit', function(event) {
scope.$apply(function() {
element.addClass('ng-submitted');
form.$submitted = true;
if (form.$valid) {
fn(scope, {
$event: event
});
}
});
});
scope.$watch(function() {
return form.$valid
}, function(isValid) {
if (form.$submitted == false)
return;
if (isValid) {
element.removeClass('has-error').addClass('has-success');
} else {
element.removeClass('has-success');
element.addClass('has-error');
}
});
}
};
}
};
}
];
app.directive('validSubmit', ValidSubmit);
I cant figure out what is the problem.
Thanks in advance.
Try changing your ngClick button handler to an ngSubmit form handler and wiring that up. You didn't say what browser you're using, but most of them auto-submit forms on an ENTER keypress unless you trap it (which you aren't). Clicking a button won't do this.