AngularJS difference between 2 dates - javascript

I have an APP(The app is built using springboot for the API and AngularJs for the view.) that gets a report for when an incidente started and finished, startdate(2015-12-01T08:19:00.000Z) and enddate(2015-12-06T02:59:00.000Z) as examples.
I dont seem to find a good way to set the difference between the two dates to a new value unavailability.
This is my .js file:
.controller(
'IncidenteController',
[
'$scope',
'$http',
'$routeParams',
'urlinc',
'$location',
function($scope, $http, $routeParams, urlinc, $location) {
var url = urlinc.getUrlinc();
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var code = $routeParams.codename;
console.log(code);
var onTecnicoComplete = function(response) {
$scope.tecnicos = response.data;
};
var onHardwareComplete = function(response) {
$scope.hardwares = response.data;
};
var onSoftwareComplete = function(response) {
$scope.softwares = response.data;
};
var onSistemaComplete = function(response) {
$scope.sistemas = response.data;
};
var onIncidenteComplete = function(response) {
try {
$scope.incidente = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(url + code)
.then(onIncidenteComplete, onError);
$http.get("http://localhost:8080/tecnico/").then(
onTecnicoComplete);
$http.get("http://localhost:8080/hardware/").then(
onHardwareComplete);
$http.get("http://localhost:8080/software/").then(
onSoftwareComplete);
$http.get("http://localhost:8080/sistema/").then(
onSistemaComplete);
$scope.saveIncidente = function(incidente) {
console.log(incidente);
return $http.post(url, incidente).success(
function(data, status, headers, config) {
var status2 = '/' + status + '/';
$location.url(status2);
return status.data;
}).error(function(status) {
var status2 = '/' + status.status + '/';
console.log(status2);
$location.url(status2);
return status.data;
})
};
$scope.hardwares = [];
$scope.hardwareListener = function() {
console.log($scope.hardwares);
}
$scope.tecnicoListener = function() {
console.log($scope.incidente.tecnico);
}
$scope.date = new Date();
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
var that = this;
this.dates = {
apertura: new Date(),
cierre: new Date(),
};
this.open = {
apertura: false,
cierre: false,
};
// Disable weekend selection
this.disabled = function(date, mode) {
return (mode === 'day' && (new Date().toDateString() == date.toDateString()));
};
this.dateOptions = {
showWeeks: false,
startingDay: 1
};
this.timeOptions = {
readonlyInput: false,
showMeridian: false
};
this.dateModeOptions = {
minMode: 'year',
maxMode: 'year'
};
this.openCalendar = function(e, date) {
that.open[date] = true;
};
// watch date1 and date2 to calculate difference
this.calculateWatch = $scope.$watch(function() {
return that.dates;
}, function() {
if (that.dates.apertura && that.dates.cierre) {
var diff = that.dates.apertura.getTime() - that.dates.cierre.getTime();
that.dayRange = Math.round(Math.abs(diff/(1000*60*60*24)))
} else {
that.dayRange = 'n/a';
}
}, true);
$scope.$on('$destroy', function() {
that.calculateWatch();
});
} ])
EDIT : This is how i managed to make it work:
$scope.calcularIndisponibilidad = function(incidente){
var cierre = incidente.cierre;
var apertura = incidente.apertura;
var date1 = Date.parse(cierre);
var date2 = Date.parse(apertura);
var difference = date1 - date2;
console.log(difference);
var daysDifference = Math.floor(difference/1000/60/60/24);
difference -= daysDifference*1000*60*60*24
var hoursDifference = Math.floor(difference/1000/60/60);
difference -= hoursDifference*1000*60*60
var minutesDifference = Math.floor(difference/1000/60);
difference -= minutesDifference*1000*60
var indisponibilidad = 'difference = ' + daysDifference + ' day/s ' + hoursDifference + ' hour/s ' + minutesDifference + ' minute/s ';
console.log(indisponibilidad);

I would suggest two ways
1. Manually calcuating
Answered before Calculate difference between 2 timestamps using javascript
2. Using Moment.js
moment().format('MMMM Do YYYY, h:mm:ss a'); // December 15th 2015, 11:14:37 am

Related

Thingworx Gantt Chart error as "TypeError: Cannot read property 'ActualDataRows' of undefined"

I am using Gantt Chart extension from PTC Marketplace. When I configured and run the mashup it's giving error as "TypeError: Cannot read property 'ActualDataRows' of undefined at resize". (Please refer the below code and the attached image file).
I this.resize function throwing an error as thisWidget.lastData is undefined. As I am new to JavaScript I am unable to solve this error. Could you guys please help me.
Thanks
(function () {
TW.Runtime.Widgets.ganttChart = function () {
var thisWidget = this;
var currentlySelectedRow = undefined;
this.runtimeProperties = function () {
return {
'needsDataLoadingAndError': true,
'supportsAutoResize': true,
'propertyAttributes': {
}
};
};
this.renderHtml = function () {
if (this.properties.ResponsiveLayout === true ) {
widgetWidth = '100%';
widgetHeight = '100%';
} else {
widgetWidth = this.getProperty("Width");
widgetHeight = this.getProperty("Height");
}
var html = '<div class="widget-content widget-ganttChart"><div id = "chart_div" width=' + widgetWidth + ' height=' + widgetHeight + '> </div></div>';
return html;
};
this.loadChart = function (rows, taskId, taskName, startDate, endDate, resource, relationships, duration, percentage) {
google.charts.load('current', {'packages':['gantt']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task ID');
data.addColumn('string', 'Task Name');
data.addColumn('string', 'Resource');
data.addColumn('date', 'Start Date');
data.addColumn('date', 'End Date');
data.addColumn('number', 'Duration');
data.addColumn('number', 'Percent Complete');
data.addColumn('string', 'Dependencies');
var trackStyle = TW.getStyleFromStyleDefinition(thisWidget.getProperty('TrackStyle', 'DefaultGanttTrackStyle'));
var altTrackStyle = TW.getStyleFromStyleDefinition(thisWidget.getProperty('AlternativeTrackStyle', 'DefaultAlternativeGanttTrackStyle'));
var arrowStyle = TW.getStyleFromStyleDefinition(thisWidget.getProperty('ArrowStyle', 'DefaultGanttArrowStyle'));
var trackFill = trackStyle.backgroundColor;
var altTrackFill = altTrackStyle.backgroundColor;
var arrowColor = arrowStyle.lineColor;
var arrowWidth = arrowStyle.lineThickness;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
data.addRows([
[row[taskId], row[taskName], row[resource],
new Date(row[startDate]), new Date(row[endDate]), row[duration], row[percentage], row[relationships]]
]);
}
var barHeight = thisWidget.getProperty('ItemHeight');
var chartHeight = rows.length * barHeight + 50;
var itemHeight = barHeight - 5;
var cornerRadius = thisWidget.getProperty('BarCornerRadius');
var percentEnabled = thisWidget.getProperty('ShowPercentCompletion');
var arrowRadius = thisWidget.getProperty('ArrowRadius');
var arrowAngle = thisWidget.getProperty('ArrowAngle');
var options = {
width: "100%",
height: chartHeight,
gantt: {
barHeight: itemHeight,
trackHeight: barHeight,
barCornerRadius: cornerRadius,
arrow: { angle:arrowAngle, length: 5, spaceAfter: 5, radius: arrowRadius, color: arrowColor, width: arrowWidth},
innerGridTrack: {fill: trackFill },
innerGridDarkTrack: {fill: altTrackFill},
percentEnabled : percentEnabled
}
};
var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', function(e) {
var selection = chart.getSelection();
if (selection[0] != undefined && selection[0] != null)
thisWidget.handleRowSelection (selection[0].row);
});
}
};
this.afterRender = function () { };
this.handleSelectionUpdate = function (propertyName, selectedRows, selectedRowIndices) {
var domElementId = this.jqElementId;
var widgetElement = this.jqElement;
var widgetProperties = this.properties;
if (propertyName == "Data") {
var widgetProperties = this.properties;
var idField = widgetProperties['TaskID'];
thisWidget.ignoreSelectionEvent = true;
var nSelectedRows = selectedRows.length;
if (nSelectedRows > 0) {
for (var x = 0; x < nSelectedRows; x++) {
if (selectedRows[x]._isSelected === true) {
thisWidget.handleRowSelection(selectedRows[x]["_row_"]);
thisWidget.ignoreSelectionEvent = false;
break;
}
}
} else
thisWidget.handleRowSelection(undefined);
thisWidget.ignoreSelectionEvent = false;
}
};
this.handleRowSelection = function (selectedRowNo) {
if (selectedRowNo !== undefined) {
var selectedRows = [selectedRowNo];
if (!thisWidget.ignoreSelectionEvent) {
thisWidget.updateSelection('Data', selectedRows);
}
}
thisWidget.currentlySelectedRow = selectedRowNo;
};
this.handleItemClick = function (d) {
thisWidget.handleRowSelection(d["_row_"]);
};
this.assignRowNumbers = function (rows) {
var rowid;
for (rowid in rows) {
var row = rows[rowid];
row["_row_"] = rowid;
}
};
this.updateProperty = function (updatePropertyInfo) {
var widgetProperties = this.properties;
if (updatePropertyInfo.TargetProperty === "Data") {
thisWidget.lastData = updatePropertyInfo;
var rows = updatePropertyInfo.ActualDataRows;
this.assignRowNumbers(rows);
var taskName = widgetProperties['TaskName'];
var taskId = widgetProperties['TaskID'];
var startDate = widgetProperties['StartDate'];
var endDate = widgetProperties['EndDate'];
var resource = widgetProperties['Resource'];
var relationships = widgetProperties['Relationships'];
var duration = widgetProperties['Duration'];
var percentage = widgetProperties['Percentage'];
this.loadChart(rows, taskId, taskName, startDate, endDate, resource, relationships, duration, percentage);
var selectedRowIndices = updatePropertyInfo.SelectedRowIndices;
if (selectedRowIndices !== undefined) {
if (selectedRowIndices.length > 0) {
var selectedRows = new Array();
selectedRows.push(rows[selectedRowIndices[0]]);
setTimeout(function () {
thisWidget.handleSelectionUpdate("Data", selectedRows, selectedRowIndices);
}, 100);
} else {
setTimeout(function () {
thisWidget.handleSelectionUpdate("Data", [], []);
}, 100);
}
} else {
setTimeout(function () {
thisWidget.handleSelectionUpdate("Data", [], []);
}, 100);
}
if (this.SelectedValuePending !== undefined) {
this.selectItem(this.SelectedValuePending);
this.SelectedValuePending = undefined;
}
} else if (updatePropertyInfo.TargetProperty === "SelectedValue") {
var selectedItem = updatePropertyInfo.SinglePropertyValue;
var dataPropertyInfo = thisWidget.lastData;
if (dataPropertyInfo != undefined) {
this.selectItem(selectedItem);
} else {
this.SelectedValuePending = selectedItem;
}
}
};
this.beforeDestroy = function () {
};
this.resize = function () {
var taskName = thisWidget.getProperty('TaskName');
var taskId = thisWidget.getProperty('TaskID');
var startDate = thisWidget.getProperty('StartDate');
var endDate = thisWidget.getProperty('EndDate');
var resource = thisWidget.getProperty('Resource');
var relationships = thisWidget.getProperty('Relationships');
var duration = thisWidget.getProperty('Duration');
var itemHeight = thisWidget.getProperty("ItemHeight");
var percentage = thisWidget.getProperty("Percentage");
var rows = thisWidget.lastData.ActualDataRows; //here throwing error
thisWidget.loadChart(rows, taskId, taskName, startDate, endDate, resource, relationships, duration, percentage);
};
window.addEventListener("resize", this.resize);
};} ());
This problem caused because I haven't assigned Trigger Event to data service used for a Gantt Chart. In this case assign 'Mashup Loaded' Trigger Event to data service.
Thanks

angularjs re-initialize directive

I have the following code
HTML
<countdown ng-show="vm.inhotel" init-val="vm.finishtime" init-lastmess="''" init-mess="'Sjekk ut'"></countdown>
Controller
vm.finishtime = 0;
vm.inhotel = false;
$rootScope.$on('enterhotel', function(data) {
console.log(data);
console.log("entering hotel for " + data.totime);
vm.inhotel = true;
vm.finishtime = new Date().getTime() + 60 * 60 * 24 * 1000;
});
Countdown directory
angular
.module('users')
.directive('countdown', countdown);
function getFormattedTime(secs) {
var date = new Date(null);
date.setSeconds(secs);
return date.toISOString().substr(11, 8);
}
function countdown() {
return {
restrict: 'E',
template: '<div class=\"{{class}}\" style=\"{{isfloating}} margin-right:5px;\""><span style=\"font-size:{{firstsize}}px;\">{{firstmess}}</span> <span style=\"font-size:{{initsize}}px;\">{{result}}</span></div>',
scope: {
initVal: '=',
initMess: '=',
initLastmess: '=',
initMesssize: '=',
initSize: '=',
initIsfloating: '=',
},
controller: function($scope, $interval) {
if ($scope.initIsfloating) {
$scope.isfloating = 'float:left;';
} else {
$scope.isfloating = '';
}
if ($scope.initLastmess == 'undefined') {
$scope.initLastmess = '';
}
$scope.countdownVal = $scope.initVal;
$scope.countdownVal = Math.floor($scope.countdownVal / 1000) - Math.floor(Date.now() / 1000);
var b = getFormattedTime($scope.countdownVal);
$scope.class = "";
$scope.firstsize = $scope.initMesssize;
$scope.initsize = $scope.initSize;
$scope.firstmess = $scope.initMess;
if ($scope.countdownVal > 0) {
$scope.result = b + " " + $scope.initLastmess;
} else {
$scope.class = "";
$scope.result = "00:00:00 " + $scope.initLastmess;
}
$interval(function () {
$scope.firstsize = $scope.initMesssize;
$scope.initsize = $scope.initSize;
$scope.firstmess = $scope.initMess;
if ($scope.initIsfloating) {
$scope.isfloating = 'float:left;';
} else {
$scope.isfloating = '';
}
if ($scope.initLastmess == 'undefined') {
$scope.initLastmess = '';
}
if ($scope.countdownVal > 0) {
$scope.class = "";
$scope.countdownVal = $scope.initVal;
$scope.countdownVal = ($scope.initVal / 1000) - Math.floor(Date.now() / 1000);
$scope.result = getFormattedTime($scope.countdownVal) + " " + $scope.initLastmess;
} else {
$scope.class = "";
$scope.result = " 00:00:00 " + $scope.initLastmess;
}
}, 1000);
}
}
};
but the countdown wont change the new finishtime object. is it possible to reinitialize the countdown directive to refresh it with my new countdown?

JavaScript function array return undefined

I am using AJAX to get the data and make them into an array like below:
function drawDate(username, date, device, token){
$.ajax({
type: 'GET',
url: dsu + "dataPoints/" + getDatapointId(username, date, device),
headers: {
"Authorization": "Bearer " + token
},
success : function(data, device) {
var location_events = []; //***** Here is the array variable.
if(device == "android" || device == "ios") {
rows = data["body"]["episodes"].map(function (epi) {
var state = epi["inferred-state"].toLocaleUpperCase();
var start = new Date(epi["start"]);
var end = new Date(epi["end"]);
var long_lat = epi["location-samples"];
if (state == "STILL") {
var longitude_sum = 0;
var latitude_sum = 0;
long_lat.forEach(function(obj) {
longitude_sum += obj['longitude'];
latitude_sum += obj['latitude'];
});
return [state, start, end, latitude_sum / long_lat.length, longitude_sum / long_lat.length];
}
});
//**** I pushed the data into the array.
rows.forEach(function(obj){
if (typeof obj !== 'undefined') {
location_events.push({
title: 'location',
start: moment(obj[1]).format().substring(0, 19),
end: moment(obj[2]).format().substring(0, 19),
url: "https://maps.googleapis.com/maps/api/staticmap?center="+ obj[3] + "," + obj[4] + "&zoom=15&size=2000x1000&maptype=roadmap&markers=color:red%7Clabel:S%7C" + obj[3] + "," + obj[4] + "&markers=size:mid"
})
}
});
console.log(location_events);
return location_events
}
},
error: function(data){
console.log('Data did not have any locations.')
}
});
}
Then when I tried to call that function, it returned "undefined". I actually want to put that array into FullCalendar like below:
$(document).ready(function() {
var today = moment();
var token = url("#access_token");
$.getJSON(dsu + "oauth/check_token?token=" + token)
.done(function(data) {
var username = data["user_name"];
var device = 'android';
var date = url("#date")? moment(url("#date")).toDate() : new Date();
var redraw = function(){
var test = drawDate(username, moment(date).format('YYYY-MM-DD'), device, token);
console.log(test); //***** Here! I tried to make the return of the function into a variable but it returned "undefined"
};
$('#calendar').fullCalendar({
header: '',
defaultDate: '2015-08-03',
defaultView: 'agendaDay',
allDaySlot: false,
slotEventOverlap: false,
events: test, //******* I want to the array to be rendered here.
eventAfterRender: function(event, element, view) {
$(element).attr("id", "event_id_" + event.id);
}
});
})
.fail(function() {
console.log("Fail!");
});
I read most of the similar questions and it seems that I should use callback function but I don't really understand how to use them.
Thank you very much! Any help is welcome!
The problem is that you do AJAX request which is asynchronous and you cannot return this data from drawDate() function. You need to do what you need with data retrieved from server in your 'success' callback. Like following:
success : function(data, device) {
var location_events = []; //***** Here is the array variable.
if(device == "android" || device == "ios") {
rows = data["body"]["episodes"].map(function (epi) {
var state = epi["inferred-state"].toLocaleUpperCase();
var start = new Date(epi["start"]);
var end = new Date(epi["end"]);
var long_lat = epi["location-samples"];
if (state == "STILL") {
var longitude_sum = 0;
var latitude_sum = 0;
long_lat.forEach(function(obj) {
longitude_sum += obj['longitude'];
latitude_sum += obj['latitude'];
});
location_events = [state, start, end, latitude_sum / long_lat.length, longitude_sum / long_lat.length];
}
});
//**** I pushed the data into the array.
rows.forEach(function(obj){
if (typeof obj !== 'undefined') {
location_events.push({
title: 'location',
start: moment(obj[1]).format().substring(0, 19),
end: moment(obj[2]).format().substring(0, 19),
url: "https://maps.googleapis.com/maps/api/staticmap?center="+ obj[3] + "," + obj[4] + "&zoom=15&size=2000x1000&maptype=roadmap&markers=color:red%7Clabel:S%7C" + obj[3] + "," + obj[4] + "&markers=size:mid"
})
}
});
console.log(location_events);
}
$('#calendar').fullCalendar({
header: '',
defaultDate: '2015-08-03',
defaultView: 'agendaDay',
allDaySlot: false,
slotEventOverlap: false,
events: location_events,
eventAfterRender: function(event, element, view) {
$(element).attr("id", "event_id_" + event.id);
}
});
}

angularjs- calling method of one controller in another

Hi I am working on a project where I have a button for subscribe/unsubscribe notification.I am using bootstrap modal on this button click and if user selects ok I perform the required operation.Everything is working fine just in the end in order to refresh my list I need to call method my another controller.I tried using $emit-$on but unable to use that.Please help how to call my GetAssignedIssues() method of myIssuesController from ModalInstanceCtrl controller.
angularjs code
//controller1
var myIssuesController = function($scope, $sce, $http, cfpLoadingBar, deviceDetector, $filter, $modal, $log) {
$("#navMyIssues").addClass("active");
$scope.issueCommnets = null;
$scope.showComments = false;
$scope.Issues = [];
$scope.dateFormat = 'dd-MMM-yyyy';
$scope.dateTimeFormat = 'dd-MMM-yyyy h:mm:ss a';
$scope.selectedIssue = null;
$scope.statusName = null;
$scope.ProjectDetails = [];
$scope.selectedProject = null;
$scope.isVisible = false;
$scope.isVisibleReply = false;
$scope.notifiedMembers = null;
$scope.defaultProfileImagePath = "";
//get all assigned issues
$scope.GetAssignedIssues = function() {
alert('test');
//$scope.issueCount = -1;
$scope.issuesLoaded = false;
$scope.issueDetailsLoaded = false;
$scope.query = "";
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/GetAllAssignedIssues/';
$http.post(url, []).success(function(data, status, headers, config) {
if (data != '' || data.length == 0) {
$scope.Issues = data;
$scope.Issues = $filter('orderBy')($scope.Issues, 'CreatedOn', true);
for (var count = 0; count < $scope.Issues.length; count++) {
if ($scope.Issues[count].StatusName == "Pending") {
$scope.pendingIssueCount = $scope.pendingIssueCount + 1;
} else if ($scope.Issues[count].StatusName == "In Progress") {
$scope.inprogressIssueCount = $scope.inprogressIssueCount + 1;
} else if ($scope.Issues[count].StatusName == "Limitation") {
$scope.limitationIssueCount = $scope.limitationIssueCount + 1;
} else if ($scope.Issues[count].StatusName == "Needs Research") {
$scope.needsresearchIssueCount = $scope.needsresearchIssueCount + 1;
} else if ($scope.Issues[count].StatusName == "In Testing") {
$scope.intestingIssueCount = $scope.intestingIssueCount + 1;
}
}
if (data.length != 0) {
if ($scope.selectedIssue == null) {
$scope.selectedIssue = $scope.Issues[0];
} else {
for (var count = 0; count < $scope.Issues.length; count++) {
if ($scope.Issues[count].Id == $scope.selectedIssue.Id) {
$scope.selectedIssue = $scope.Issues[count];
}
}
}
}
$scope.issuesLoaded = true;
$scope.showIssueDetails($scope.selectedIssue);
} else {
$scope.errors.push(data.error);
//$scope.issueCount = -1;
}
if ($scope.isVisible == false) {
$("#changedetailsbox").hide();
$scope.isVisible = true;
}
if ($scope.isVisibleReply == false) {
$("#postReplybox").hide();
$scope.isVisibleReply = true;
}
}
);
};
$scope.$on("eventAssignedIssues", function (event,args) {
alert('test1');
$scope.GetAssignedIssues();
});
};
//controller 2
var ModalInstanceCtrl = function ($scope, $modalInstance,modalHeader,modalBody,issueId,issueEmailId,$http) {
$scope.modalHeader=modalHeader;
$scope.modalBody=modalBody;
$scope.issueId=issueId;
$scope.issueEmailId=issueEmailId;
$scope.ok = function () {
if($scope.modalHeader=="Delete Issue")
{
}
else if($scope.modalHeader=="Subscribe")
{
var issueNotification = { issueId: $scope.issueId, email: $scope.issueEmailId };
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/SubscribeIssueNotification/';
$http.post(url, JSON.stringify(issueNotification)).success(function (data, status, headers, config) {
if (data == "true" || data == true) {
//$scope.GetAssignedIssues();
$scope.$root.broadcast("eventAssignedIssues",{});
} else {
$scope.errors.push(data.error);
}
$scope.showeditdesc = true;
});
}
else if($scope.modalHeader=="Unsubscribe")
{
//for unsubscribing
var issueId = $scope.issueId;
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/UnsubscribeIssueNotification/';
$http.post(url, JSON.stringify({ issueId: issueId })).success(function (data, status, headers, config) {
if (data == "true" || data == true) {
//$scope.GetAssignedIssues();
$scope.$root.broadcast("eventAssignedIssues",{});
} else {
$scope.errors.push(data.error);
}
$scope.showeditdesc = true;
});
}
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
use $rootScope.broacast() if you want to communication between two sibbling controllers
Please Refer this link wonderful explanation
http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
using the service , factory , value will serve you the purpose of sharing data
using of $emit and $broadcast will do the job for you ,which is as shown below
function firstCtrl($scope,$rootScope) {
$scope.broadcast = function(bcMsg){
$scope.broadcastMsg = bcMsg;
$rootScope.$broadcast('broadC',$scope.broadcastMsg);
}
$rootScope.$on('emitC',function(events,data){
$scope.emitMsg = data;
});
}
//second controller
myApp.controller('secondCtrl',secondCtrl);
//inject dependencies
secondCtrl.$inject = ["$scope","$rootScope"];
function secondCtrl($scope,$rootScope) {
$scope.$on('broadC',function(events,data){
$scope.broadcastMsg=data;
});
$rootScope.$on('emitC',function(events,data){
$scope.emitMsg = data;
});
}
http://jsfiddle.net/shushanthp/w4pwkkcq/
sharing the data between the controller using directives is also possible using require in the directive Using "require" in Directive to require a parent Controller
To understand events read this article- enter link description here
I have found the solution with #Shubham Nigam help,so thanks to him too-firstly we need to define $rootScope in both controllers and use $on and $broadcast using $rootScope.Here is my updated code
Answer
//controller1
var myIssuesController = function($rootScope,$scope, $sce, $http, cfpLoadingBar, deviceDetector, $filter, $modal, $log) {
$("#navMyIssues").addClass("active");
$scope.issueCommnets = null;
$scope.showComments = false;
$scope.Issues = [];
$scope.dateFormat = 'dd-MMM-yyyy';
$scope.dateTimeFormat = 'dd-MMM-yyyy h:mm:ss a';
$scope.selectedIssue = null;
$scope.statusName = null;
$scope.ProjectDetails = [];
$scope.selectedProject = null;
$scope.isVisible = false;
$scope.isVisibleReply = false;
$scope.notifiedMembers = null;
$scope.defaultProfileImagePath = "";
//get all assigned issues
$scope.GetAssignedIssues = function() {
alert('test');
//$scope.issueCount = -1;
$scope.issuesLoaded = false;
$scope.issueDetailsLoaded = false;
$scope.query = "";
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/GetAllAssignedIssues/';
$http.post(url, []).success(function(data, status, headers, config) {
if (data != '' || data.length == 0) {
$scope.Issues = data;
$scope.Issues = $filter('orderBy')($scope.Issues, 'CreatedOn', true);
for (var count = 0; count < $scope.Issues.length; count++) {
if ($scope.Issues[count].StatusName == "Pending") {
$scope.pendingIssueCount = $scope.pendingIssueCount + 1;
} else if ($scope.Issues[count].StatusName == "In Progress") {
$scope.inprogressIssueCount = $scope.inprogressIssueCount + 1;
} else if ($scope.Issues[count].StatusName == "Limitation") {
$scope.limitationIssueCount = $scope.limitationIssueCount + 1;
} else if ($scope.Issues[count].StatusName == "Needs Research") {
$scope.needsresearchIssueCount = $scope.needsresearchIssueCount + 1;
} else if ($scope.Issues[count].StatusName == "In Testing") {
$scope.intestingIssueCount = $scope.intestingIssueCount + 1;
}
}
if (data.length != 0) {
if ($scope.selectedIssue == null) {
$scope.selectedIssue = $scope.Issues[0];
} else {
for (var count = 0; count < $scope.Issues.length; count++) {
if ($scope.Issues[count].Id == $scope.selectedIssue.Id) {
$scope.selectedIssue = $scope.Issues[count];
}
}
}
}
$scope.issuesLoaded = true;
$scope.showIssueDetails($scope.selectedIssue);
} else {
$scope.errors.push(data.error);
//$scope.issueCount = -1;
}
if ($scope.isVisible == false) {
$("#changedetailsbox").hide();
$scope.isVisible = true;
}
if ($scope.isVisibleReply == false) {
$("#postReplybox").hide();
$scope.isVisibleReply = true;
}
}
);
};
$rootScope.$on('eventAssignedIssues', function (event, args) {
$scope.GetAssignedIssues();
});
};
//controller 2
var ModalInstanceCtrl = function ($rootScope,$scope, $modalInstance,modalHeader,modalBody,issueId,issueEmailId,$http) {
$scope.modalHeader=modalHeader;
$scope.modalBody=modalBody;
$scope.issueId=issueId;
$scope.issueEmailId=issueEmailId;
$scope.ok = function () {
if($scope.modalHeader=="Delete Issue")
{
}
else if($scope.modalHeader=="Subscribe")
{
var issueNotification = { issueId: $scope.issueId, email: $scope.issueEmailId };
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/SubscribeIssueNotification/';
$http.post(url, JSON.stringify(issueNotification)).success(function (data, status, headers, config) {
if (data == "true" || data == true) {
//$scope.GetAssignedIssues();
$rootScope.$broadcast('eventAssignedIssues');
} else {
$scope.errors.push(data.error);
}
$scope.showeditdesc = true;
});
}
else if($scope.modalHeader=="Unsubscribe")
{
//for unsubscribing
var issueId = $scope.issueId;
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/UnsubscribeIssueNotification/';
$http.post(url, JSON.stringify({ issueId: issueId })).success(function (data, status, headers, config) {
if (data == "true" || data == true) {
//$scope.GetAssignedIssues();
$rootScope.$broadcast('eventAssignedIssues');
} else {
$scope.errors.push(data.error);
}
$scope.showeditdesc = true;
});
}
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};

Twitter Jquery Widget: Creating invalid URLS

I have a twitter widget on my website. The only problem is, it is creating invalid URLS for the link when you click on the "about 5 hours ago.."
Example: If you click on a recent tweet it takes you to this link, which is invalid: http://twitter.com/#!/ohshititsjake/statuses/63741419709411330
The correct url is:
http://twitter.com/#!/ohshititsjake/statuses/63741419709411328
Here is the part of the script I believe is the problem:
` function build_url() {
var proto = ('https:' == document.location.protocol ? 'https:' : 'http:');
if (s.list) {
return proto+"//api.twitter.com/1/"+s.username[0]+"/lists/"+s.list+"/statuses.json?per_page="+s.count+"&callback=? ";
} else if (s.query == null && s.username.length == 1) {
return proto+'//api.twitter.com/1/statuses/user_timeline.json?screen_name='+s.username[0]+'&count='+s.count+'&callback=?';
} else {
var query = (s.query || 'from:'+s.username.join(' OR from:'));
return proto+'//search.twitter.com/search.json?&q='+escape(query)+'&rpp='+s.count+'&callback=?';
}
}
`
Here is the full javascript:
(function($) {
$.fn.tweet = function(o){
var s = {
username: ["ohshititsjake"],
list: null,
avatar_size: 20,
count: 3,
intro_text: null,
outro_text: null,
join_text: null,
auto_join_text_default: "I said:<br/>",
auto_join_text_ed: "I",
auto_join_text_ing: "I said:<br/>",
auto_join_text_reply: "I replied to",
auto_join_text_url: "I was looking at",
loading_text: null,
query: null
};
if(o) $.extend(s, o);
$.fn.extend({
linkUrl: function() {
var returning = [];
var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?)/gi;
this.each(function() {
returning.push(this.replace(regexp,"$1"));
});
return $(returning);
},
linkUser: function() {
var returning = [];
var regexp = /[\#]+([A-Za-z0-9-_]+)/gi;
this.each(function() {
returning.push(this.replace(regexp,"#$1"));
});
return $(returning);
},
linkHash: function() {
var returning = [];
var regexp = /(?:^| )[\#]+([A-Za-z0-9-_]+)/gi;
this.each(function() {
returning.push(this.replace(regexp, ' #$1'));
});
return $(returning);
},
capAwesome: function() {
var returning = [];
this.each(function() {
returning.push(this.replace(/\b(awesome)\b/gi, '<span class="awesome">$1</span>'));
});
return $(returning);
},
capEpic: function() {
var returning = [];
this.each(function() {
returning.push(this.replace(/\b(epic)\b/gi, '<span class="epic">$1</span>'));
});
return $(returning);
},
makeHeart: function() {
var returning = [];
this.each(function() {
returning.push(this.replace(/(<)+[3]/gi, "<tt class='heart'>♥</tt>"));
});
return $(returning);
}
});
function parse_date(date_str) {
// The non-search twitter APIs return inconsistently-formatted dates, which Date.parse
// cannot handle in IE. We therefore perform the following transformation:
// "Wed Apr 29 08:53:31 +0000 2009" => "Wed, Apr 29 2009 08:53:31 +0000"
return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
}
function relative_time(time_value) {
var parsed_date = parse_date(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
var pluralize = function (singular, n) {
return '' + n + ' ' + singular + (n == 1 ? '' : 's');
};
if(delta < 60) {
return 'less than a minute ago';
} else if(delta < (60*60)) {
return 'about ' + pluralize("minute", parseInt(delta / 60)) + ' ago';
} else if(delta < (24*60*60)) {
return 'about ' + pluralize("hour", parseInt(delta / 3600)) + ' ago';
} else {
return 'about ' + pluralize("day", parseInt(delta / 86400)) + ' ago';
}
}
function build_url() {
var proto = ('https:' == document.location.protocol ? 'https:' : 'http:');
if (s.list) {
return proto+"//api.twitter.com/1/"+s.username[0]+"/lists/"+s.list+"/statuses.json?per_page="+s.count+"&callback=? ";
} else if (s.query == null && s.username.length == 1) {
return proto+'//api.twitter.com/1/statuses/user_timeline.json?screen_name='+s.username[0]+'&count='+s.count+'&callback=?';
} else {
var query = (s.query || 'from:'+s.username.join(' OR from:'));
return proto+'//search.twitter.com/search.json?&q='+escape(query)+'&rpp='+s.count+'&callback=?';
}
}
return this.each(function(i, widget){
var list = $('<ul class="tweet_list">').appendTo(widget);
var intro = '<p class="tweet_intro">'+s.intro_text+'</p>';
var outro = '<p class="tweet_outro">'+s.outro_text+'</p>';
var loading = $('<p class="loading">'+s.loading_text+'</p>');
if(typeof(s.username) == "string"){
s.username = [s.username];
}
if (s.loading_text) $(widget).append(loading);
$.getJSON(build_url(), function(data){
if (s.loading_text) loading.remove();
if (s.intro_text) list.before(intro);
var tweets = (data.results || data);
$.each(tweets, function(i,item){
// auto join text based on verb tense and content
if (s.join_text == "auto") {
if (item.text.match(/^(#([A-Za-z0-9-_]+)) .*/i)) {
var join_text = s.auto_join_text_reply;
} else if (item.text.match(/(^\w+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+) .*/i)) {
var join_text = s.auto_join_text_url;
} else if (item.text.match(/^((\w+ed)|just) .*/im)) {
var join_text = s.auto_join_text_ed;
} else if (item.text.match(/^(\w*ing) .*/i)) {
var join_text = s.auto_join_text_ing;
} else {
var join_text = s.auto_join_text_default;
}
} else {
var join_text = s.join_text;
};
var from_user = item.from_user || item.user.screen_name;
var profile_image_url = item.profile_image_url || item.user.profile_image_url;
var join_template = '<span class="tweet_join"> '+join_text+' </span>';
var join = ((s.join_text) ? join_template : ' ');
var avatar_template = '<a class="tweet_avatar" href="http://twitter.com/'+from_user+'"><img src="'+profile_image_url+'" height="'+s.avatar_size+'" width="'+s.avatar_size+'" alt="'+from_user+'\'s avatar" title="'+from_user+'\'s avatar" border="0"/></a>';
var avatar = (s.avatar_size ? avatar_template : '');
var date = '<span class="tweet_time">'+relative_time(item.created_at)+'</span>';
var text = '<span class="tweet_text">' +$([item.text]).linkUrl().linkUser().linkHash().makeHeart().capAwesome().capEpic()[0]+ '</span>';
// until we create a template option, arrange the items below to alter a tweet's display.
list.append('<li>' + avatar + date + join + text + '</li>');
list.children('li:first').addClass('tweet_first');
list.children('li:odd').addClass('tweet_even');
list.children('li:even').addClass('tweet_odd');
});
if (s.outro_text) list.after(outro);
$(widget).trigger("loaded").trigger((tweets.length == 0 ? "empty" : "full"));
});
});
};
})(jQuery);
Looking at the permalink's IDs on that user account, they don't match with the IDs getting generated in your post. The answer is probably in this post:
Why a wrong tweet id is returned from twitter API?
so try changing this line:
var date = '<span class="tweet_time">'+relative_time(item.created_at)+'</span>';
to this:
var date = '<span class="tweet_time">'+relative_time(item.created_at)+'</span>';
Really, it's just changing item.id to item.id_str.in the middle of that line.

Categories