I am new to AngularJS and I am experimenting with particular javascript file which I am trying to integrate into the angularJS.
my index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script type="text/javascript" src="https://docs.handsontable.com/0.16.1/scripts/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<script type="text/javascript"src="https://docs.handsontable.com/0.16.1/bower_components/handsontable/dist/handsontable.full.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<link type="text/css" rel="stylesheet" href="https://docs.handsontable.com/0.16.1/bower_components/handsontable/dist/handsontable.full.min.css">
</head>
<body >
<div id="example1" class="hot handsontable htRowHeaders htColumnHeaders" dragResize></div>
</body>
</html>
My app.js
angular.module('myApp',[]).directive('dragResize',function(){
return{
restrict: 'EA',
controller: function($scope, $timeout){
//document.addEventListener("DOMContentLoaded", function() {
var
container = document.getElementById('example1'),
hot;
hot = new Handsontable(container, {
data: Handsontable.helper.createSpreadsheetData(200, 10),
rowHeaders: true,
colHeaders: true,
colWidths: [55, 80, 80, 80, 80, 80, 80],
rowHeights: [50, 40, 100],
manualColumnResize: true,
manualRowResize: true
});
function bindDumpButton() {
if (typeof Handsontable === "undefined") {
return;
}
Handsontable.Dom.addEvent(document.body, 'click', function (e) {
var element = e.target || e.srcElement;
if (element.nodeName == "BUTTON" && element.name == 'dump') {
var name = element.getAttribute('data-dump');
var instance = element.getAttribute('data-instance');
var hot = window[instance];
console.log('data of ' + name, hot.getData());
}
});
}
bindDumpButton();
$timeout(dragResize,0);
//});
}
};
});
I am not sure whether I am doing it right. I tried to run the file but it displayed nothing. I have couple of queries:-
1. How to call the controller in my index.html?
2. Is there the better way to embed the javascript file?
3. Which would be better choice creating a factory and exposing the dependency or creating custom directive?
Would appreciate some knowledge sharing on the problem.
thanks..
Angular is two way binding. So you don't need to inflate any view say DIV with id example1 in your code.
You can create scope to reflect your output using $scope or $rootScope.
And If you want to do this using document.getElementById("") then better go with normal js file instead controller in AngularJS.
And as you have asked :: MultiController in index.html
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp">
<div ng-controller="myCtrl">
First Name:
<input type="text" ng-model="firstName">
<br> Last Name:
<input type="text" ng-model="lastName">
<br>
<br> Full Name: {{firstName + " " + lastName}}
</div>
<div ng-controller="myCtrl2">
First Name:
<input type="text" ng-model="firstName2">
<br> Last Name:
<input type="text" ng-model="lastName2">
<br>
<br> Full Name: {{firstName + " " + lastName}}
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
app.controller('myCtrl2', function($scope) {
$scope.firstName2 = "asdf";
$scope.lastName2 = "asdfdsf";
});
</script>
</body>
</html>
Related
I am using Mustache to generate pages based on Data.
My problem: I need to getElementbyid in the page generated by Mustache. However, it always returns NULL. Do you have any ideas how I can fix it ? (I left a comment in main.js in the part where I am having issues.)
3 pages to reproduce my case:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="test-id">
<!-- Generated Content -->
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
<script src="mustache.js"></script>
<script src="../node_modules/file-system/file-system.js"></script>
</body>
</html>
template_page.html (where Mustache generate a page based on Data)
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="template-div">
<!-- part filled by Mustache -->
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
<script src="mustache.js"></script>
<script src="../node_modules/file-system/file-system.js"></script>
</body>
</html>
And the javascript part
main.js
document.addEventListener('DOMContentLoaded', function() {
// I get NULL but I want to find a way to get a None null value !!!
console.log(document.getElementById("test-get-id-value"));
// Data to get the different pages
var ALL_DATA = [
{
'lastname': 'lastname_1',
'firstname': 'firstname_1'
},
{
'lastname': 'lastname_2',
'firstname': 'firstname_2'
},
{
'lastname': '"lastname_3"',
'firstname': 'firstname_3'
}
];
// Function to get the different links
function displayData(obj_name) {
var theDiv = document.getElementById("test-id");
obj_name.forEach(doc => {
var lastname = doc['lastname'];
var firstname = doc['firstname'];
newdiv = document.createElement("div")
var text = document.createTextNode(lastname + ' ' + firstname);
var anchor_value = document.createElement("a")
url = lastname + firstname + '.html'
anchor_value.setAttribute("href", "template_page.html" + "?firstname=" + firstname + "&lastname=" + lastname);
anchor_value.setAttribute("class", "link-a");
anchor_value.onclick = createPage();
anchor_value.appendChild(document.createTextNode("Contact him"));
newdiv.appendChild(text);
newdiv.appendChild(anchor_value);
theDiv.appendChild(newdiv);
});
};
displayData(ALL_DATA);
// Function to create the PAGE based on the Data
function createPage() {
// get url parameters
var url = new URL(window.location.href);
var firstname_value = url.searchParams.get("firstname");
var lastname_value = url.searchParams.get("lastname");
// get the data needed
data = {
'lastname': lastname_value,
'firstname': firstname_value
};
var template =
`
<h1> Welcome, {{firstname}} </h1>
<h2> Your last name: {{lastname}} </h2>
<form id="test-get-id-value">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
`
var html = Mustache.render(template, data);
$("#template-div").html(html);
};
});
Your listener for DOMContentLoaded fires when you first load your page, and at that instant, no html has been rendered by Mustache
You can get the non-null value only after the template is rendered, so execute all your logic after render of the template:
var html = Mustache.render(template, data);
$("#template-div").html(html);
var el = document.getElementById("test-get-id-value");
// Now run the logic you need
Sorry for the possible repost, but I don't know how else to write this. I've been using this website to create a small angularJS webpage using nodeJS as well, and I've gotten to the part of separating the angular code from the view, or HTML. What I've found was that when I tried to separate them nothing worked any more.
Here's my code so far:
Home.html:
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<!-- <script>
var myApp = angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.myColor = "red";
});
</script> -->
</head>
<body>
<!-- <script>
myApp.directive('myDirective', function() {
return {
template: "This is a test directive."
};
})
</script> -->
<h2>myApp Test</h2>
<div ng-app="myApp" ng-controller="myCtrl" ng-init="quantity = 10; cost = 5">
<p>Color: <input type="text" style="background-color:{{myColor}}" ng-model="myColor" value="{{myColor}}"></p>
<p>Total in dollar (raw exp): {{quantity * cost}}</p>
<p>Total in dollar (span): <span ng-bind="quantity * cost"></span></p>
<p> First Name: <input type="text" ng-model="firstName"></p>
<p> Last Name: <input type="text" ng-model="lastName"></p>
<h1>Hello, {{firstName + " " + lastName}}</h1>
</div>
Are you even changing?!
</body>
<script type="javascript" src="../JS/myApp.js"></script>
<!-- <script type="javascript" src="../JS/myApp.module.js"></script> -->
<script type="javascript" src="../JS/myCtrl.js"></script>
<!-- <script type="javascript" src="../JS/myCtrl.component.js"></script> -->
</html>
myApp.js / myApp.module.js:
var myApp = angular.module('myApp', []);
myCtrl.js / myCtrl.component.js:
myApp.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.myColor = "red";
});
// app.directive('myDirective', function() {
// return {
// template: '<p><h3>This is a test directive.<h3></p>'
// };
// });
Finally, here's my folder hierarchy:
If what I've done wrong is already evident, there's no need for you to continue reading.
Now the commented-out code is important as well. These are both the other things I've tried, and what I wanted to implement. I have tried:
Re-adding all the angular code back to the head tag to make sure it was still working at all. It worked, aside from the directive stuff (which, at point, I believe would have to be part of a separate module, but not the point, nonetheless).
Moving the script references, which are, and were, located below the body, to the head.
Moving the script references to the top of the body.
Moving everything into just *one* file (myApp.module.js).
Renaming both "myCtrl.component.js" and "myApp.module.js" to "myCtrl.js" and "myApp.js", respectively, to ensure possibly-antiquated angularJS nomenclature wasn't an attribution.
Adding "type="javascript"" to the script references.
"Hard refreshing" to make sure old documents weren't cached.
Tested to see if it was even requesting the files from the server using node. It doesn't look like it is.
If you need the nodeJS part of it, it's here as well (index.js):
var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');
http.createServer(function(req, res) {
var myUrl = url.parse(req.url);
var basename = path.basename(myUrl.path);
console.log('request url: ' + req.url);
console.log('url path: ' + myUrl.path);
console.log('basename: ' + basename);
fs.readFile('../HTML/Home.html', function(err, data) {
res.writeHead(200, { 'ContentType': 'text/html' });
res.write(data);
res.end();
});
}).listen(8080);
The problem is in your script tag
<script type="javascript" src="../JS/myCtrl.js"></script>
It should not be
type="javascript"
Either change it to
type="text/javascript"
or remove the type totally. Due to incorrect type , it is not loading controller and other js files to browser.
<!DOCTYPE html>
<html ng-app="myApp" >
<head>
<title>myApp.html</title>
</head>
<body ng-controller="myCtrl as vm">
<br><br>
<div>
<p> Inserisci un colore <input style="background-color:{{colore}}" ng-model="colore" value="{{colore}}"> </p>
<body bgcolor="{{colore}}">
</div>
<div >
<p>Nome: <input style="background-color:{{colore}}" type="text" id="nome" onkeyup="" ng-model="vm.utente.nome"></p>
<p>Cognome: <input style="background-color:{{colore}}" type="text" id="cognome" ng-model="vm.utente.cognome"></p>
<p id="prova" value="test">{{myFunction}}</p>
<p>{{vm.saluta() | uppercase}}</p>
</div>
<p id="demo">prova</p>
<button onclick= vm.myFunction()> Prova</button>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript" src="C:\Users\user1\Desktop\myCtrl.js"></script>
</body>
</html>
myCtrl.js
(function() {
'use strict';
var app = angular.module('myApp', []);
app.controller('myCtrl', function() {
var vm=this;
vm.utente = {nome: "Mario", cognome: "Rossi"};
vm.saluta = function() {
return "Buongiorno " +
this.utente.nome + " " +
this.utente.cognome + "!"
};
vm.myFunction = function() {
var text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = text.toUpperCase();
};
function test2() {
console.log("Hello!");
};
});
})();
i'm new on AngularJS and i can't understand my error. I see a lot of example in a single file (html with tag script) but i prefer to separate the controller with the html file.
in my mind, I intended to connect the controller without scope, simply replacing "this" with vm (var vm = this). I just want to do some simple tests with the functions, but i always get this error:
myApp.html: 30 Uncaught ReferenceError: vm is not defined at
HTMLButtonElement.onclick (myApp.html: 30)
the first function work normally, i get the response from the "vm.saluto()" only if i call with the format: {{vm.saluto}}. why onclick and other not work?
Any help?
where is my mistake?
I am aware of the many cases similar to this, I have already displayed, but I have not found the solution
Your example, overall, should work.
Be aware that you have two body tags.
More importantly you should understand that the vm name you defined in controller as is not the same as the vm variable, which is local to your controller's function.
Finally you should avoid direct DOM manipulations when using AngularJS.
See example below:
(function() {
'use strict';
var app = angular.module('myApp', []);
app.controller('myCtrl', function() {
var vm = this;
vm.utente = {
nome: "Mario",
cognome: "Rossi"
};
vm.saluta = function() {
return "Buongiorno " +
this.utente.nome + " " +
this.utente.cognome + "!"
};
vm.test = 'prova';
vm.myFunction = function() {
vm.test = vm.test.toUpperCase();
};
function test2() {
console.log("Hello!");
};
});
})();
<html ng-app="myApp">
<body ng-controller="myCtrl as vm">
<p>{{vm.utente.nome}}</p>
<p>{{vm.saluta()}}</p>
<button type="button" ng-click="vm.myFunction()">test</button>
<p id="demo">{{ vm.test }}</p>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
The index.html page looks like this.
<!DOCTYPE html>
<html ng-app>
<head>
<script type="text/javascript" src="/js/script.js"/>
<script data-require="angular.js#*" data-semver="1.3.0-beta.14" src="http://code.angularjs.org/1.3.0-beta.14/angular.js"></script>
<meta charset="UTF-8">
<title>Test Page</title>
</head>
<body ng-controller="MainController">
<div>
<h1>{{message}}</h1>
<div>
{{person.firstName}}
</div>
</div>
</body>
</html>
The script.js file looks like this:
var MainController = function($scope) {
var person = {
firstName : "Nagendra"
};
$scope.person = person;
$scope.message = "Hello Angular!";
};
But when I boot up the application my page shows :
{{message}}
{{person.firstName}}
and not the values that it should. Am I missing something here? I am using spring boot.
I have debugged the chrome and have seen the js file loading properly, it even hits the debugger point in the js file,hence the file loading is not the problem i suppose.
UPDATE- THIS WORKED
var MainController = function($scope) {
var person = {
firstName: "Nagendra"
};
$scope.person = person;
$scope.message = "Hello Angular!";
};
angular.module('mainApp', [])
.controller('MainController', MainController);
index.html
<!DOCTYPE html>
<html ng-app="mainApp">
<head>
<script data-require="angular.js#*" data-semver="1.3.0-beta.14" src="http://code.angularjs.org/1.3.0-beta.14/angular.js"></script>
<script type="text/javascript" src="/js/script.js"></script>
<meta charset="UTF-8">
<title>Test Page</title>
</head>
<body ng-controller="MainController">
<div>
<h1>{{message}}</h1>
<div>
{{person.firstName}}
</div>
</div>
</body>
</html>
Since angular 1.3+ global function declaration of controller haven't been supported. So you have first create an angular module and then bind all of its angular component to it.
Also move /js/script.js right after angular.js reference with closing </script> tag.
Code
angular.module('mainApp', [])
.controller('MainController', MainController)
function MainController($scope) {
var person = {
firstName: "Nagendra"
};
$scope.person = person;
$scope.message = "Hello Angular!";
};
Then do add mainApp module inside ng-app directive like ng-app="mainApp" on html tag.
Demo Here
You need to define the module and the controller,
HTML:
<body ng-app="DemoApp" ng-controller="DemoController">
{{message}} {{person.firstName}}
</body>
Controller:
var app = angular.module('DemoApp', ['angular.filter'])
app.controller('DemoController', function($scope) {
var person = {
firstName : "Nagendra"
};
$scope.person = person;
$scope.message = "Hello Angular!";
});
DEMO
So I referred to this link http://demo.jankuri.com/ngGallery/ to make image gallery.
I did everything as directed but nothing shows up as in no images are shown.
Here is my Controller
var check123 = function() {
for (var i = 0; i < z; i++) {
var a = {thumb: '../images/offers/'+'123456789/thumbnails/' + objectidphoto[i], img: '../images/offers/'+'123456789/' + objectidphoto[i]};
arr.push(a);
}
console.log(arr);
console.log(arr[0]);
}
This is not my complete controller only the significant part.
This is my front end code
<body ng-app="fileUpload" ng-controller="MyCtrl">
<div>
<div class="content">
<ng-gallery images="MyCtrl.arr"></ng-gallery>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script src="controller14.js"></script>
<script src="ng-infinite-scroll.js"></script>
<script src="ng-infinite-scroll.min.js"></script>
<script type="text/javascript" src="src/js/ngGallery.js"></script>
</body>
The angular code executes without any errors and I am getting proper response in return for that console.log(arr).
What am I doing wrong?
Updated Segment
Controller
var app = angular.module('fileUpload', ['jkuri.gallery']).
controller('MyCtrl', function($scope, $document)
{
var self = this;
self.images = [
{thumb: 'images/offers/'+'123456789/thumbnails/' + '1445524452873_491676259.jpg', img: '../images/offers/'+'123456789/' + '1445524452873_491676259.jpg'},
{thumb: 'images/offers/'+'123456789/thumbnails/' + '1445524894340_7a668c73cddcd2050821f83be901832a_1426070017.jpg', img: '../images/offers/'+'123456789/' + '1445524894340_7a668c73cddcd2050821f83be901832a_1426070017.jpg'}
];
});
HTML
<body ng-app="fileUpload" ng-controller="MyCtrl">
<div>
<ng-gallery images="MyCtrl.images"></ng-gallery>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script src="controller14.js"></script>
<script src="ng-infinite-scroll.js"></script>
<script src="ng-infinite-scroll.min.js"></script>
<script type="text/javascript" src="src/js/ngGallery.js"></script>
</body>
Now I have exactly replicated what the module's demo looks like. Still the problem is there. There is no change on the front end.
You reference Myctrl.arr , you do not need to prefix the controller name. Just arr should work, that is, if you're correctly assigning arr to the scope. $scope.arr.push ...
I'm going to take a guess you're doing neither of the above.
UDATED:
Your controller:
var app = angular.module('fileUpload', ['jkuri.gallery']). controller('MyCtrl', function($scope, $document) { $scope.images = [ {thumb: 'images/offers/'+'123456789/thumbnails/' + '1445524452873_491676259.jpg', img: '../images/offers/'+'123456789/' + '1445524452873_491676259.jpg'}, {thumb: 'images/offers/'+'123456789/thumbnails/' + '1445524894340_7a668c73cddcd2050821f83be901832a_1426070017.jpg', img: '../images/offers/'+'123456789/' + '1445524894340_7a668c73cddcd2050821f83be901832a_1426070017.jpg'} ]; });
Your html
<body ng-app="fileUpload" ng-controller="MyCtrl"> <div> <ng-gallery images="images"></ng-gallery> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script> <script src="controller14.js"></script> <script src="ng-infinite-scroll.js"></script> <script src="ng-infinite-scroll.min.js"></script> <script type="text/javascript" src="src/js/ngGallery.js"></script> </body>
Note the $scope assignment and the lack of the controller name.