When I trigger deleteQuestion() a second time 2 questions get deleted. Any idea? Let me know if you need to see more of my code.
controller.js
crtPromoCtrl.controller('surveyCtrl', ['$scope', 'surveySrv', function($scope, surveySrv)
{
$scope.questions = surveySrv.getQuestions();
$scope.editQuestion = function(index)
{
surveySrv.setEditQuestion(index);
};
$scope.deleteQuestion = function(index)
{
$(document).off('click', '#confirmationModal #confirm');
$('#confirmationModal').modal('show');
$(document).on('click', '#confirmationModal #confirm', function()
{
surveySrv.deleteQuestion(index);
$scope.$apply();
});
};
}]);
service.js
crtPromoSrv.service('surveySrv', function()
{
var questions = [];
var editQuestion;
this.getQuestions = function()
{
return questions;
};
this.addQuestion = function(question)
{
questions.push(question);
};
this.setEditQuestion = function(index)
{
editQuestion = questions[index];
};
this.getEditQuestion = function()
{
return editQuestion;
};
this.clearEditQuestion = function()
{
editQuestion = undefined;
};
this.deleteQuestion = function(index)
{
questions.splice(index, 1);
console.log(questions);
};
});
EDIT: I'm thinking it's an event propagation thing, since when I have 5 q's it deletes #2 and #3 when I delete #2.
EDIT: Fixed, see controller.js code.
It appears you are adding the 'click' function to your #confirmationModal #confirm button multiple times. The first time $scope.deleteQuestion is called, it adds the function. The second time you call it, it adds it again so when it is clicked, the function is called twice.
A simple fix would be to unbind the 'click' event before adding it again. Something like this: $('#confirmationModal #confirm').off('click');
The better solution here is to not use jQuery at all for these event bindings. Using a simple Angular modal directive (like the one provided in the Angular-UI library, for instance) would be the correct way to do this. Then you can just have an ng-click on the button and never have this problem.
Related
I have a function 'highlightBookmark' that should change the background color of a list item after 2 seconds. But it doesn't work!!!
It changes 'li' background only if the function is called by click event. It doesn't change it automatically after time is out, even if it actually calls the function.
Here is my code:
Controller.js
//markers
$scope.markers = [
{
time: 9.5,
text: "Bookmark 1",
class: false
},
{
time: 106,
text: "Bookmark 2",
class: false
}
]
$scope.currentBookmark = -1;
function highlightBookmark(index) {
$scope.markers[index].class = true;
}
var interval = setInterval(checkTime, 100);
function checkTime(){
if(Math.floor(player.currentTime()) == 2){
highlightBookmark(1)
clearInterval(interval);
}
}
$scope.jumpTo = function (index) {
highlightBookmark(index);
}
The highlight function, takes in an integer, looks for object at that position and updates set 'class' parameter to true. Example, if I pass number 1 to the function, it will look for object at index 2 and set the 'class property' to be true.
Then, after 2 seconds I want to call the highlightBookmark function. IT IS CALLED but it doesn't update the class, thus the background doesn't update.
I call the same with click event and it works.
HTML file
<ul id = "bookmarkList">
<li ng-repeat="bookmark in markers" ng-class="{'active': bookmark.class}" ng-click="jumpTo($index)">{{bookmark.text}}</li>
</ul>
This li has the ng-class property that I want to change after 2 seconds.
Here is a link to a similar code I did on codepen. It changes button color on click, but doesn't change on setTimeout even if method is called
https://codepen.io/Octtavius/pen/wgzORv
Could somebody help with this simple issue?
The vanilla setInterval function doesn't update scope variables. Try with the $interval API by Angular:
var interval = $interval(checkTime, 100);
function checkTime(){
if(Math.floor(player.currentTime()) == 2){
highlightBookmark(1)
interval.cancel();
}
}
Notice clearInterval(interval) changes to interval.cancel()
Also don't forget to inject it as dependency.
Fair point by charlietfl: Also cancel the interval if the scope gets destroyed.
Place this inside your controller:
$scope.$on("$destroy", function( event ) {
interval.cancel( timer );
});
More info: https://docs.angularjs.org/api/ng/service/$interval
setInteral and setTimeout run outside of the angular digest cycle, so they will not be properly picked up by Angular.
Consider using the $timeout object in your controller -- this gives you the timeout functionality but allows angular to keep an eye on it.
You should consider use angular $timeout instead of setInverval or setTimeout.
Because:
This functions don't $digest the $scope variables;
$timeout in this case requires less memory to do the exactly same thing that $interval would do.
So, this part of your controller will look like this:
//markers
$scope.markers = [
{
time: 9.5,
text: "Bookmark 1",
class: false
},
{
time: 106,
text: "Bookmark 2",
class: false
}
]
$scope.currentBookmark = -1;
function highlightBookmark(index) {
$scope.markers[index].class = true;
}
$timeout(checkTime, 2000);
function checkTime(){
highlightBookmark(1);
}
$scope.jumpTo = function (index) {
highlightBookmark(index);
}
Remember to inject the $timeout as a dependency in your controller.
P.S.
This code will mark a default after 2 seconds, you don't give enough details so I can know what the player is doing. So if you want to improve this, give more details and we can make it happen.
You should consider use "controller as". Here is a link to John Papa's article about it. https://johnpapa.net/angularjss-controller-as-and-the-vm-variable/
And if you want to toggle the background on click event you should use this code. Cause the one you did is only adding the background, but not removing from the others li. To do this we need to modify the html and the controller a little bit:
<div ng-app="classApp" ng-controller="classCtrl">
<ul id = "bookmarkList">
<li ng-repeat="bookmark in markers" ng-class="{'active': selectedMarker === bookmark}" ng-click="jumpTo(bookmark)">{{bookmark.text}}</li>
</ul>
</div>
$scope.selectedMarker = null;
function highlightBookmark(marker) {
$scope.selectedMarker = marker;
}
$timeout(checkTime, 2000);
function checkTime(){
highlightBookmark($scope.markers[0])
}
$scope.jumpTo = function (marker) {
highlightBookmark(marker);
}
Cya.
var classApp = angular.module('classApp', []);
classApp.controller('classCtrl', function ($scope, $timeout) {
$scope.isActive = false;
$scope.activeButton = function () {
$scope.isActive = !$scope.isActive;
}
function checkTime() {
$scope.isActive = !$scope.isActive;
}
$timeout(checkTime, 2000)
});
Got a very odd issue coming up here with the new components. When we had a 1.4 directive we had the following code...
(function () {
'use strict';
angular.module('app.board').directive('dcCb', dcClipboardCopy);
function dcCb() {
return {
link : function(scope, elem) {
var clipboard = new Clipboard(elem[0]);
elem.on('$destroy', function() {
clipboard.destroy();
});
}
};
}
})();
Inside the clipboard.destroy() function is the following...
Clipboard.prototype.destroy = function(){
this.listeners.destroy();
}
In 1.4 this is the same as the element so...
<button class="btn btn-sm btn-menu-outline copy-button" ...
So this worked fine as the button element seemed to have the listeners property which could be invoked.
However after the upgrade to 1.5 and now we have a component like this....
(function() {
'use strict';
angular.module('app.board').component('dcCb', {
...
controller: [ '$element','$scope',function($element,$scope) {
var self = this;
self.$postLink = postLink;
function postLink(){
var clipboard = new Clipboard($element[0]);
...
$element.on('$destroy', clipboard.destroy);
}
}]
});
})();
this (when inside the destroy function of the Clipboard) is now the controller object. So trying to call this.listeners throws an error.
First Question :
I understand that this in new components is the component scope but in 1.4 it was the button element. Surely in both the button element should be $element? Were we doing something wrong in 1.4?
Second Question :
Shouldn't var clipboard = new Clipboard($element[0]) force the context of this inside the clipboard to always be the clipboard itself (due to the new keyword)?
You're handing a function, which is arbitrarily defined on a class, off to the window and event listeners to be executed in a different context than the instance of Clipboard:
$element.on('$destroy', clipboard.destroy);
This is a fundamental concept of execution context in javascript, and I'd recommend reading up on it. But you can easily solve your current problem by simply binding the context of the function you are passing:
$element.on('$destroy', clipboard.destroy.bind(clipboard));
I'm familiar with using something like:
$scope.gotoBottom = function(){
$location.hash('bottom');
$anchorScroll();
}
and this works.. yet what I'm seeing is an issue when retrieving data that's being used in an ng-repeat and attempting to resize when that data comes in.
Example (in controller):
users.get({userList:$routeParams.conversationId}, function(data){
$scope.userList = data;
$scope.gotoBottom();
})
The gotoBottom method is firing to fast, while the ng-repeat is looking on $scope.userList and buidling it's table based off that.
I want to be able to toggle gotoBottom after that list has been remade (or whenever it's modified). Is there a better way to achieve this?
Thank you!
You can use $watch listener to fire gotoBotton when an AngularJs variable change.
$scope.ActivityList = new Array();
$scope.$watch("ActivityList", function () {
$scope.$evalAsync(function () {
$scope.DoSomething();
});
}, true);
$scope.DoSomething = function () {
$(function () {
//$scope.gotoBottom();
});
};
Also you can run scrolling bottom after page is loaded
angular.element($window).bind('load',
function() {
var element = document.getElementById("messages-list").lastElementChild;
element.id = "bottom";
/*-------------*/
$location.hash('bottom');
$anchorScroll();
}
OK, I've done some reading on this and I'm pretty sure I know what the problem relates to I Just don't know the best way to fix it. I've got the standard backbone router that sets me up with an item details view, then when I click on a button called "start" it creates a new view which takes me to a sort of a game that people can play with some buttons on the bottom that have "click" events attached. This second view is not called through the router but directly from the first view.
The problem is the second time someones goes back to the homescreen and does it again, this time there are two events attached to each button. The third time there are three events. Obviously the original views are still listening to these buttons. I've read about this and calling the Remove() method but is this what I need to do? If so where do I call remove? Relevant Code below:
1ST VIEW
window.GameDrillView = Backbone.View.extend({
initialize: function () {
this.render();
},
render: function () {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
events: {
"click .start" : "startGameDrill",
},
startGameDrill: function () {
var start = $('#start').val();.
var stop = $('#stop').val();.
var StartView = new GameDrillStartView({model: this.model, el: $('#content')[0], start: start, stop:stop});
}
});
START VIEW
window.GameDrillStartView = Backbone.View.extend({
// declare variables
initialize: function () {
this.render();
},
events: {
"click .nextstage" : "nextstage", // 2ND TIME THROUGH GETS CALLED TWICE
},
nextstage: function () {
// Do some stuff //
this.render(); //Re-render
},
render: function () {
// Do some variables stuff
this.$el.html(this.template(jQuery.extend(this.model.toJSON(), extended_options)));..
return this;
}
});
When changing view you need to call undelegateEvents() method from the Backbone.View. It disable listening all the elements events mentioned in events { } block. Also if you need to destroy old view you can call remove() method of the view which will call undelegateEvents() internally.
update (example from official site)
var Workspace = Backbone.Router.extend({
routes: {
"help": "help", // #help
"search/:query": "search", // #search/kiwis
"search/:query/p:page": "search" // #search/kiwis/p7
},
help: function() {
if (this.currentView)
this.currentView.undelegateEvents();
this.currentView = new HelpView();
},
search: function(query, page) {
if (this.currentView)
this.currentView.undelegateEvents();
this.currentView = new SearchView();
}
});
An option is to create only one instance of the view:
if(_.isUndefined(this.StartView))
this.StartView = new GameDrillStartView({model: this.model, el: $('#content')[0], start: start, stop:stop});
else
this.StartView.render();
In the render method of GameDrillStartView add the empty method
this.$el.html(this.template(jQuery.extend(this.model.toJSON(), extended_options)))
In this way you won't add more event listeners but you'll update the page everytime the user presses the button.
You can manage the life cycle of StartView in GameDrillView since it seems like a better place to do so.
Got same trouble. Messy solution:
var current_view = false;
var prev_view = false;
var AppRouter = Backbone.Router.extend({
routes: {
"events/:id": "viewEvent",
}
});
var app_router = new AppRouter;
app_router.on('route:viewEvent', function (event_id) {
var _event = new Event({id:event_id});
current_view = new EventView({
model: _event,
});
});
//Will be called after route:viewEvent
app_router.on('route', function () {
if(prev_view) {
prev_view.undelegateEvents();
}
prev_view = current_view;
});
Not sure, how to make it without having current_view and prev_view out of router scope.
I am setting some setInterval values on my widget's controller code as follows:
define(['durandal/widget'],function (widget) {
var count = 0;
var intervals = [],
ctor = function (element, settings) {
this.settings = settings;
};
ctor.prototype.updateCount = function( ){
var interval = setInterval(function () {
count = count + 1;
return count;
}, 1000);
intervals.push(interval);
}
return ctor;
}
The above code is being run inside a forEach loop inside the view like:
<div data-bind="foreach: {data: settings.items}">
<span class="count" data-bind="text:$parent.updateCount()"></span>
</div>
What I would like to do is call the clearInterval method on all the items in the intervals array when the widget is destroyed or essentially removed from the dom. I know I could do this using the deactivate on a viewModel but from a reusability point of view, I would like the widget itself to handle the clearing of interval. Is there any way I could achieve this with the widget module in Durandal.
For anyone else looking into the same issue, there's a knockout way of achieving the same. Have a look at the following links https://github.com/BlueSpire/Durandal/issues/139 and https://groups.google.com/forum/#!topic/durandaljs/NqUkY-9us2g . The suggestion is to use:
ko.utils.domNodeDisposal.addDisposeCallback(element, callback)
As long as the widget is removed with JQuery's "remove" function, adding a custom event handler on this "remove" function should go like this:
var self = this;
var self.count = 0;
var self.intervals = [];
self.ctor = function (element, settings) {
$(element).on("remove", function () {
$.each(self.intervals, function(index, ival) {
clearInterval(ival);
});
});
this.settings = settings;
};
The problem is that if the widget is removed without JQuery, simply by manipulating the DOM, the event will not be fired. You could then implement the code for the DOMNodeRemoved event, but it's not gonna work for IE...
Edit: if you're using JQuery pre-1.9.1, you might want to check out the other answers to this question.