Elements of Angular stop to respond after a time - angularjs

Hy every one!
I'm using in this project Angular 1.6.5 because my workteam think is better.
But I found an error with angular elements. In all forms of my app They stop the behaviour after a time. That is, it doesn't save date when i click in button save, ore delete. But when i refresh the page the elements start responds again. Any one have idea why?
In the project we are using a library to control style css. the problem may be there?
here is one piece of my html code
<div class="col-4-1">
<p class="link"><a class="btn-pri" href ng-click="savePartner()" ng-if="enableSaveBtn">Save</a></p>
<p class="link"><a class="btn-pri remove-link btn-red-50" href ng-click="delPartner()" ng-if="enableDelBtn">Erase</a></p>
</div>
pice controller code:
$scope.addLabelToPartner = function() {
$scope.partner.LabelList = $scope.partner.mcnList || [];
$scope.partner.LabelList.push($scope.partner.code);
$scope.partner.code = "";
};
$scope.delLabelFromPartner = function(idx) {
$scope.partner.LabelList.splice(idx, 1);
};
$scope.savePartner = function() {
$scope.saveErr = false;
WebService.createPartner($scope.partner).then(
function(response) {
common.widget.overlay.hide("overlayPartnerForm");
$scope.fetchAllPartners();
},
function(error) {
$scope.saveErr = true;
}
);
};
$scope.delPartner = function() {
$scope.saveErr = false;
WebService.deletePartner($scope.partner._id).then(
function(response) {
common.widget.overlay.hide("overlayPartnerForm");
$scope.fetchAllPartners();
},
function(error) {
$scope.saveErr = true;
}
);
};

Related

Hiding page loader only after completion of data load in the page view

Currently am working with angularjs.
now i have an ng-click function,it is called when checkbox is checked or unchecked. i have a full page loader and when i click on the check box it will be displayed. It will be hidden only after loading the complete view. I tried this code and it is not working
here comes the click
<input type="checkbox"id="myId" ng-click="sampleClick(1)">
here is the js code
$scope.sampleClick = function(type) {
var param = new Object();
param.type = type;
//side bar listing
Data.post('url/testurl', param).then(function(data){
$scope.all = '';
$scope.all = angular.fromJson(data);
console.log("Contents is trying to load.");
$scope.$on('$viewContentLoaded',function(event, viewConfig){
console.log("Contents did load.");
$rootScope.setVariable = 1;
});
}, function (error) {
$rootScope.setVariable = 1;
});
}
I want to set the $rootScope.setVariable = 1 only when the view section is completely loaded.(and each time when I click on the check box)
Note : when I use $viewContentLoaded at the time of page load, it works without any issue. But when I use the same along with the ng-click function, i don't get any response.
If the view is rendered using ng-repeat, why can't you use ng-repeat directive to handle the end of render and then initiate a function call.
for example
<div ng-repeat="i in things" repeat-done>
// here you use i to render your filter with checkbox
</div>
and directive will look like
app.directive('repeatDone', function($rootScope) {
return function(scope, element, attrs) {
if (scope.$last){
//set your variables or do you job
}
};
})
You can set one flag you can set it value true/false.
for example(I am taking your example so you can understand it batter):-
$scope.loading = false;
$scope.sampleClick = function(type) {
var param = new Object();
param.type = type;
//side bar listing
Data.post('url/testurl', param).then(function(data){
$scope.all = '';
$scope.all = angular.fromJson(data);
console.log("Contents is trying to load.");
$scope.loading = true;
$scope.$on('$viewContentLoaded',function(event, viewConfig){
$scope.loading = false;
console.log("Contents did load.");
$rootScope.setVariable = 1;
});
}, function (error) {
$rootScope.setVariable = 1;
});
}
here i have take $scope.loading variable which default value is false, when you click on checkbox then it will be set to true so at that time you can show the loader and when it get the data it will be set to false so it will stops loading.
I hope you understand.

Firechat changes route in angularJS

I'm trying to implement Firechat in angularJS and have come across a weird issue.
After the chat initialises the angular route changes to the Firechat room name.
e.g I am initially on http://localhost/app/#/stream
and when firechat loads the route changes to
http://localhost/app/#/-KBLofTk2mb6AJCTSc5C
I can't seem to figure out how or why firechat is changing the route. Any advice would be great :)
Here is the code I am using to run fireChat:
$scope.goFireChat = function() {
var chatRef = new Firebase('https://blazing-fire-3021.firebaseio.com'),
target = document.getElementById("firechat-wrapper"),
chat = new FirechatUI(chatRef, target);
chatRef.onAuth(function(authData) {
if (authData) {
var userId = authData.uid,
userName = "Anonymous" + userId.substr(10, 8);
chat.setUser(userId, userName);
$timeout(function() {
chat._chat.enterRoom('-KBLofTk2mb6AJCTSc5C');
}, 2000);
} else {
$timeout(function() {
chat._chat.enterRoom('-KBLofTk2mb6AJCTSc5C');
}, 2000);
}
});
}

Refreshing FullCalendar upon saving events with Angular Resource $save

I'm building a calendar inspired by this example http://plnkr.co/edit/pIDltQRV6TQGD4KQYnj7?p=preview and adding $save to add new events using RESTful server connection.
I'm trying to find a way to make the calendar show the new events when they are $saved without manually refreshing the browser.
My attempt to get this to work was to add (or remove) the event data to the event array (gDataService.events). Although it does change the content of the array, the change is not shown in the calendar. (e.g., if I change the date of the event, the event won't move to the new date.)
Can someone point me in the right direction? Thanks!
HTML
<div ui-calendar="uiConfig.calendar" class="span8 calendar" ng-model="eventSources"></div>
Controller1 ... This saves new event.
$scope.ok = function () {
$scope.entry = new calFactory();
$scope.entry.data = data
$scope.entry.$save( function(){
// data saved. do something here.
toaster.pop('success','Message','Update successfully completed.');
});
};
Controller2 ... Main controller that defines eventSource
myApp.controller("MainCtrl", function($scope,$compile,uiCalendarConfig, calFactory,eventFactory, gDataService) {
gDataService.events = function(start, end, callback) {
var d = new Date(start);
var events;
events = calFactory.query({
start: start,
end: end
});
events.$promise.then(function(value){
gDataService.events = events;
//have to call the callback as well to keep the calendar happy
callback(gDataService.events);
$scope.statusTxt = $scope.statusTxt + " ... Event loading completed at " + moment(new Date()).format("HH:mm:ss");
}
);
};
/* event sources array*/
$scope.eventSources = [gDataService.events]; /*, $scope.eventSource, $scope.eventsF*/
})
Factory
myApp.factory("calFactory",['$resource','$filter', function($resource, $filter) {
return $resource("/griddata/", {}, {
get: {
method: 'GET'
},
save: {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: function(data, headersGetter) {
data = angular.toJson(data);
data = $.parseJSON(data);
return $.param(data.data);
}
}
});
}]);
gDataService ... This stores event data and make it available to other parts of the program
myApp.factory("gDataService", function ($rootScope, calFactory) {
var service = {};
service.events = [];
service.addData = function(object, no_broadcast) {
this.events.push({
__id: object.task_id, title: object.task, start: object.duedates,
backgroundColor: bColor, textColor: bTextColor, borderColor: bColor
});
if (!no_broadcast) {$rootScope.$broadcast("gDataUpdated")};
};
service.removeData = function(task_id, no_broadcast) {
var arr_index = _.findIndex(this.events, {'__id': task_id});
this.events.splice(arr_index, 1);
if (!no_broadcast) {$rootScope.$broadcast("gDataUpdated")};
};
return service;
});
Nobody would answer to this much sophisticated question.
You have some typos:
Missed closing with ";", "]"...
What's inside 'function calFactory'? What is '$broadcast'?
Why do you put '$' leading the JavaScript object? Is this meaning "private var"?
"if (!no_broadcast) ..." is not coding, but commenting.
In "$scope.entry.$save( function(){",
Why entry doesn't have '$', but scope and save have it?
Here is the answer from chris-rock https://github.com/angular-ui/ui-calendar/issues/200.
Changed scope.init in calendar.js like this:
scope.init = function(){
calendar.fullCalendar(options);
window.calendar = calendar; /// This is the key
};
Now I can add or remove events dynamically using window.calendar.fullCalendar('removeEvents' or 'renderEvent')!!
Here is how I changed my code.
gDataService
service.addData = function(object, no_broadcast) {
//add additional project
this.added_event = {
__id: object.task_id, title: object.task, start: object.duedates,
backgroundColor: bColor, textColor: bTextColor, borderColor: bColor
};
this.events.push(this.added_event);
if (!no_broadcast) {$rootScope.$broadcast("gDataUpdated")};
};
service.removeData = function(_id, no_broadcast) {
var arr_index = _.findIndex(this.events, {'_id': _id});
this.delete_id = _id;
this.events.splice(arr_index, 1);
if (!no_broadcast) {$rootScope.$broadcast("gDataUpdated")};
};
return service;
Controller
$scope.$on('gDataUpdated', function(){
if (gDataService.delete_id) {
window.calendar.fullCalendar('removeEvents',gDataService.delete_id); // This removes this event from the calendar
gDataService.delete_id = null;
};
if (gDataService.added_event) {
window.calendar.fullCalendar('renderEvent',gDataService.added_event,false); // This adds this event to the calendar
gDataService.added_event = null;
};

not updated template view -> it needs mous scroll, or clear input

I'm using angular.js with stomp-websockets,sock.js under by this tutorial http://g00glen00b.be/spring-websockets-angular/. I'm getting messages from websocket, but template view isn't refreshed after message from websocket is arrived. When I want to update template view I need to clear input box, or scroll with mouse.
$scope.initiator = false;
$scope.socket = {
client: null,
stomp: null
};
$scope.initSockets = function() {
$scope.socket.client = new SockJS('/myUrl');
$scope.socket.stomp = Stomp.over($scope.socket.client);
$scope.notifyMessage = function(message) {
$scope.initiator = true;
$scope.messages.push(message)
};
$scope.socket.stomp.connect({}, function() {
$scope.socket.stomp.subscribe("/topic/messages", $scope.notifyMessage);
});
$scope.socket.client.onclose = $scope.reconnect;
};
$scope.initSockets();
template view:
<ul><li ng-repeat="item in messages track by $index">{{item}}</li></ul>
You probably need to use scope.$apply to have it take effect. afaics sock.js is not made for angular, so you need to let angular know something has changed on the scope. You do this using scope.$apply.
$scope.notifyMessage = function(message) {
$scope.$apply(function(){
$scope.initiator = true;
$scope.messages.push(message)
});
};

Execute a function after two or more events are fired in Backbone

I have two buttons:
<button id="1">button 1</button>
<br>
<button id="2">button 2</button>
I want to make an alert message to appear only after the two buttons are clicked, this is part of a larger app for which I am using Backbone.js, so far I have this:
var test = {};
_.extend(test, Backbone.Events); //in order to use the backbone events feature
test.on("hello bye", function(){
alert("works!");
});
$("#1").click(function() {
test.trigger("hello");
});
$("#2").click(function() {
test.trigger("bye");
}?);
This presents the message whenever one of the two buttons are clicked, but I need it to work only after the two buttons are clicked. Is there a way to achieve this using the Backbone.Events feature or perhaps using jQuery?
Fiddle: http://jsfiddle.net/ccgRN/
Thanks
Here's an idea using promises: http://jsfiddle.net/LFJGL/1/
Edit: fixed for older browsers:
var test = {};
var promises = [];
_.extend(test, Backbone.Events); //in order to use the backbone events feature
function GetAPromise() {
var p = $.Deferred();
promises.push(p);
return p;
}
var events = "hello bye".split(" ");
_.each(events,function(event) {
var p = GetAPromise();
test.on(event, function() {
p.resolveWith(event);
});
});
$("#1").click(function() {
test.trigger("hello");
});
$("#2").click(function() {
test.trigger("bye");
});
$.when.apply($, promises).done(function() {
alert('triggered');
//might be nice to remove the event triggers here.
});​
A minimalist implementation would be to create a couple variables to keep track of what events have been fired.
var helloClicked = false;
var byeClicked = false;
var test = {};
_.extend(test, Backbone.Events);
test.on('hello bye'), function() {
if (helloClicked && byeClicked) {
alert('works!');
}
});
$('#1').click(function() {
helloClicked = true;
test.trigger('hello');
});
$('#2').click(function() {
byeClicked = true;
test.trigger('bye');
});

Resources