AngularJs dynamic Event Handling for the whole page level - angularjs

I want to create following event(s) using angularjs.
mousemove
keydown
DOMMouseScroll
mousewheel
mousedown
touchstart
touchmove
scroll
Now what I am trying is as following...,
<!DOCTYPE html>
<html ng-app="appname">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>
<body>
</body>
<script>
var app = angular.module('appname', []);
app.directive('myDirective', function() {
alert("Hello");
return {
link: function(scope, element) {
scope.appname.$on('mousemove', function() {
alert("mousemove");
});
scope.appname.$on('keydown', function() {
alert("keydown");
});
scope.appname.$on('DOMMouseScroll', function() {
alert("DOMMouseScroll");
});
});
}
});
</script>
</html>
But I cannot get it working. Let me get your suggestions.

Since each $scope inherits from the $rootScope and you are not using an isolated scope here, you can use $rootScope.$on to subscribe to the events for your whole application.
A great introduction can be found here.

After,I learned from this answer, I got it working in following code.
<!DOCTYPE html>
<html ng-app="testApp">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>
<body>
</body>
<script>
var app = angular.module('testApp', []);
app.run(['$document', function($document) {
var bodyElement = angular.element($document);
bodyElement.bind('click', function (e) {
console.log('click');
});
bodyElement.bind('mousemove', function (e) {
console.log('mousemove');
});
bodyElement.bind('keydown', function (e) {
console.log('keydown');
});
bodyElement.bind('DOMMouseScroll', function (e) {
console.log('DOMMouseScroll');
});
bodyElement.bind('mousewheel', function (e) {
console.log('mousewheel');
});
bodyElement.bind('mousedown', function (e) {
console.log('mousedown');
});
bodyElement.bind('touchstart', function (e) {
console.log('touchstart');
});
bodyElement.bind('touchmove', function (e) {
console.log('touchmove');
});
bodyElement.bind('scroll', function (e) {
console.log('scroll');
});
}]);
</script>
</html>
Demo Link

Related

AngularJS call Rest Api: TypeError

I am calling restful service from AngularJS. HTML is very basic with a input text box and a button for query.
// basic.html
<!DOCTYPE html>
<html ng-app="cgApp" >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
<script src="../js/controller.js"></script>
<script src="../js/service.js"></script>
</head>
<body>
<div ng-controller="CgseqCtrl">
<input ng-model="analysisid"><button ng-click="searchById()">Search</button>
<table>
<tr>
<td>{{seq.analysisId}}</td>
<td>{{seq.center}}</td>
<td>{{seq.diseaseAbbr}}</td>
<td>{{seq.filepath}}</td>
<td>{{seq.library}}</td>
</tr>
</table>
</div>
</body>
</html>
I use a service to call rest api
// service.js
app.factory("Cgseq", function ($http) {
// return $resource('http://localhost:8080/cgweb/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009');
var service = {};
service.getSeqById = function(analysisid) {
return http.get('http://localhost:8080/cgweb/api/seqs/' + analysisid);
}
service.getSeq = function() {
return $http.get('http://localhost:8080/cgweb/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009');
}
return service;
});
The function searchById() will be executed once the button is clicked. It is implemented in my controller.
// controller.js
var app = angular.module('cgApp', [])
app.controller('CgseqCtrl', ['$scope', 'Cgseq', function($scope, Cgseq){
$scope.searchById() = function() {
CgSeq.getSeqById($scope.analysisid)
.then(function(response){
$scope.seq = response;
});
}
}]);
When I load basic.html in a browser, even before I type in something in the input box and click the button, I got the following error:
angular.js:12416 TypeError: $scope.searchById is not a function
at new <anonymous> (controller.js:8)
You should remove the () from $scope.searchById() = function
And correct the typo (case-sensitivity) for Cgseq
I.e.:
$scope.searchById = function() {
Cgseq.getSeqById($scope.analysisid)
.then(function(response){
$scope.seq = response;
});
}

Backbone JS Button Click Event Not Working

I am new to backbone js and I'm struggling to display an alert when clicking on the button displayed in the html page. I am certain I'm doing something foolish, but when i click the button the event doesn't seem to be fired. I have tried to use both submit and click in the events section, but I can't seem to get it to work. I would be very grateful if someone could help me out, thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Event Test</title>
<script src="../../external/jquery.js"></script>
<script src="../../external/underscore.js"></script>
<script src="../../external/backbone.js"></script>
</head>
<body>
<div id="standard-input-form"></div>
<script>
var MovePalletView = Backbone.View.extend({
initialize: function() {
},
events: {
'submit' : 'move'
},
render: function(event) {
this.$el.append('<button type="button" value="Submit"></button>');
$("#standard-input-form").html(this.$el.html());
return this;
},
move: function() {
alert("You clicked it");
}
});
$(function(){
var movePalletView = new MovePalletView()
movePalletView.render();
})
</script>
</body>
</html>
In the event there are any other newbie's out there reviewing this question, this was the working code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dairy Tracker</title>
<script src="../../external/jquery.js"></script>
<script src="../../external/underscore.js"></script>
<script src="../../external/backbone.js"></script>
<script src="src/MovePallet.js"></script>
</head>
<body>
<form id="standard-input-form"></form>
<script>
var MovePalletView = Backbone.View.extend({
el: '#standard-input-form',
initialize: function () {},
events: {
'submit': 'move'
},
render: function (event) {
this.$el.append('<button type="submit" value="Submit"></button>');
return this;
},
move: function (e) {
e.preventDefault(); //this line keeps the page from refreshing after closing the following alert.
alert("You clicked it");
}
});
$(function(){
var movePalletView = new MovePalletView()
movePalletView.render();
});
</script>
</body>
</html>
Render function appends just HTML string which doesn't have any events bound. Instead append HTML element (just remove .html() part):
events: {
'click' : 'move'
},
render: function(event) {
this.$el.append('<button type="button" value="Submit"></button>');
$("#standard-input-form").html(this.$el);
return this;
},
However, this is not really a good solution, because you would have to use click event instead of proper submit. Much better approach is to initialize your MovePalletView with #standard-input-form as this.$el:
var MovePalletView = Backbone.View.extend({
el: '#standard-input-form',
initialize: function () {},
events: {
'submit': 'move'
},
render: function (event) {
this.$el.append('<button type="submit" value="Submit"></button>');
return this;
},
move: function (e) {
e.preventDefault();
alert("You clicked it");
}
});
A few notes. First of all, make sure you have button type="submit" it will trigger onsubmit event. Then you need to create View object on the form element as the root (el: '#standard-input-form'). Then you will be able to bind to its onsubmit event.

Marionette 'could not find template' - load external templates

I'm new with backbone, and also marionette. Idk why I'm get this error. My structure seems correct, but the error persists.
This is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<!-- Main App -->
<div id="main-area"></div>
<!-- Templates -->
<script id="main-tpl" src="templates/main.tpl" type="text/x-template"></script>
<!-- 3rd party Dependencies -->
<script src="vendor/jquery/dist/jquery.js"></script>
<script src="vendor/underscore/underscore.js"></script>
<script src="vendor/backbone/backbone.js"></script>
<script src="vendor/backbone.wreqr/lib/backbone.wreqr.js"></script>
<script src="vendor/backbone.babysitter/lib/backbone.babysitter.js"></script>
<script src="vendor/marionette/lib/backbone.marionette.js"></script>
<script type="text/javascript">
// External templates load
_.each(document.querySelectorAll('[type="text/x-template"]'), function (el) {
$.get(el.src, function (res) {
el.innerHTML = res;
});
});
var App = new Backbone.Marionette.Application();
_.extend(App, {
Controller: {},
View: {},
Model: {},
Page: {},
Scrapers: {},
Providers: {},
Localization: {}
});
App.addRegions({
Main: '#main-area'
});
App.addInitializer(function (options) {
var mainView = new App.View.Main();
try {
App.Main.show(mainView);
} catch(e) {
console.error('Error on Show Main: ', e, e.stack);
}
});
App.View.Main = Backbone.Marionette.Layout.extend({
template: '#main-tpl'
});
(function(App) {
'use strict';
App.start();
})(window.App);
</script>
</body>
and my template/main.tpl is only test html.
<div>sounds</div>
All 3rd party dependencies paths are correct.
The error that appears is this:
Error: Could not find template: '#main-tpl'
Can someone tell me where am I wrong?
Thanks.
EDIT:
I think the problem is because $.get is async and the template load after backbone try to render, how can I solve this?
You can update your HTML and replace
<script id="main-tpl" src="templates/main.tpl" type="text/x-template"></script>
with
<script id="main-tpl" type="text/html">
--- template code ---
</script>
Or use requireJs !text plugin to load template files into marionette views.
The problem is that the template loads after the app initialization.
Instead, try this:
$(function () {
var tplList = document.querySelectorAll('[type="text/x-template"]');
var tplCounter = 0;
_.each(tplList, function (el) {
$.ajax({
'url': el.src,
success: function (res) {
el.innerHTML = res;
++tplCounter;
if(tplCounter == tplList.length){
App.start();
}
}
});
});
});
define(['marionette','tpl!cell.tpl'],function(tpl){
var Mn = Backbone.Marionette;
var MyView = Mn.View.extend({
className: 'bg-success',
template: tpl,
regions: {
myRegion: '.my-region'
}
});
})
var model = new Backbone.Model({});
var myView = new MyView({model:model});

Phonegap with Angular: deviceready not working properly

I believe I have set everything for Angular to work in Phonegap, but apparently the deviceready function is not having the behavior that I expect.
So here is how I set:
index.html
<html ng-app="app">
<head>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/lib/ready.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
<div class="header" ng-controller="HeaderController">
<h3 id="logo"><img src="img/logo.png"/></h3>
<p>{{title}}</p>
<button ng-click="changeTitle()"></button>
</div>
</body>
</html>
app.js
$app = angular.module('app', ['fsCordova']);
$app.config(function($compileProvider){
$compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
});
$app.controller('HeaderController', function($scope, CordovaService) {
CordovaService.ready.then(function() {
console.log("Setting the title");
$scope.title = "This title";
$scope.changeTitle = function() {
console.log("Changing the title");
$scope.title = "Title changed";
}
});
});
ready.js from: http://www.ng-newsletter.com/posts/angular-on-mobile.html#native
angular.module('fsCordova', [])
.service('CordovaService', ['$document', '$q',
function($document, $q) {
var d = $q.defer(),
resolved = false;
var self = this;
this.ready = d.promise;
document.addEventListener('deviceready', function() {
resolved = true;
d.resolve(window.cordova);
});
// Check to make sure we didn't miss the
// event (just in case)
setTimeout(function() {
if (!resolved) {
if (window.cordova) d.resolve(window.cordova);
}
}, 3000);
}]);
The title is appearing the way it is {{title}}, not its value. When I click the button, nothing happens, not even the debug logs on the console. Any tips how to set Angular on Phonegap? Thanks.
Apparently on angular 1.2 the urlSanitizationWhitelist doesn't exist anymore.
So I just had to remove the $compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/); line and it worked

Backbone model not instantiated

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="backbone.js"></script>
<script type="text/javascript" src="jquery-min1.4.js"></script>
<script>
//MODEL CREATION
var person=Backbone.Model.extend(
{
initialize: function()
{
alert("hello backbone");
}
});
function perf()
{
var val=new person();
}
</script>
</head>
<body>
<button onclick="perf()">CLICK</button>
</body>
</html>
This is a simple code, alert is not invoked in the model when an instance of it is created in the perf() function which is called while clicking the button... Please help
Try to write your code in $(function() {}); block or $(document).ready(function () {}); block.
It should work.
You are missing a script reference to Underscore.js
<script type="text/javascript" src="underscore.js"></script>
Backbone requires it as a dependency.
Download it at http://underscorejs.org/ then put it above your script element for backbone.js and it will work fine.
Here's jsfiddle that included both suggestions by dcarson & Naresh J , http://jsfiddle.net/Rvn2L/1/
$(function () {
var person = Backbone.Model.extend({
initialize: function () {
alert("hello backbone");
}
});
function perf() {
console.log('1');
var val = new person();
}
window.perf = perf;
})

Resources