many functions in a controller on AngularJS? - javascript

<!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>

Related

AngularJS Webpage Can't Find Referenced Angular Module or Controller

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.

How to integrate javascript code in angularjs

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>

How to send value in JavaScript variable to a Angular js variable

I am having a problem sending a value of JavaScript variable to Angular js variable. I want to send a value in dataArray variable in JavaScript to Angular js variable $scope.test
html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="angular.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
// $("#fileUpload").load('test.csv');
$.get("test.csv", function(data) {
alert(data);
var rows = data.split("\r\n");
if(rows.length>0){
alert("inside if");
var firstRowCells = GetCSVCells(rows[0], ",");
var dataArray = new Array();
for(var i=1;i<rows.length;i++)
{
var cells = GetCSVCells(rows[i], ",");
var obj = {};
for(var j=0;j<cells.length;j++)
{
obj[firstRowCells[j]] = cells[j];
}
dataArray.push(obj);
}
$("#dvCSV").html('');
alert(dataArray);
$("#dvCSV").append(JSON.stringify(dataArray));
var myjson=JSON.stringify(dataArray);
//alert(myjson);
}
});
function GetCSVCells(row, separator){
return row.split(separator);
}
});
</script>
</head>
<body>
<div id="container">
Test
</div>
<div ng-app="sortApp" ng-controller="mainController">
<div id="dvCSV" ng-model="dataf" ng-bind="bdc">dfsgdfd</div>
</div>
<script src="app.js"></script>
</body>
</html>
app.js:
angular.module('sortApp', [])
.controller('mainController', function($scope) {
window.alert("Angular");
window.alert("asdfad"+$scope.bdc);
$scope.test=$scope.dataf;
window.alert($scope.myjson);
window.alert("test"+$scope.test.value);
You can do this all jquery stuff in angular using http service of angular js.
For simple http service you can refer this link -
http://www.w3schools.com/angular/angular_http.asp
I agree with previous answer. Also its wrong to use $(document).ready along with using angular framework in you application.
Try something like this:
angular.module('sortApp', [])
.service('loadTestCsv' ['$http', function($http) {
return $http.get('test.csv').then(data => {
// do all data processing you need
return data;
});
}]);
.controller('mainController', ['$scope', 'loadTestCsv', function($scope, loadTestCsv) {
loadTestCsv().then(data => {
$scope.data = data;
});
}]);

Change Appended each text

I'm not getting result properly using append event instead of using ng-repeat in adding each name. Can you please help me how can I change added each name from a single input field. Tell me without using ng-repeat in this, because ng-repeat functionality is not working to me for my further running functionalities, you can solve this using jquery or javascript if it's possible without using ng-repeat. Thanks in advance..
Here is JSBin
var app = angular.module('myapp', ['ngSanitize']);
app.controller('AddCtrl', function ($scope, $compile) {
$scope.my = {name: 'untitled'};
$scope.add_Name = function (index) {
var namehtml = '<label ng-click="selectName($index)">{{my.name}} //click<br/></label>';
var name = $compile(namehtml)($scope);
angular.element(document.getElementById('add')).append(name);
};
$scope.selectName = function (index) {
$scope.showName = true;
};
});
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.0-rc.0/angular-sanitize.min.js"></script>
</head>
<body ng-controller="AddCtrl">
<button ng-click="add_Name($index)">Add Names</button>
<div id="add"></div><br/>
<form ng-show="showName">
<label>Name Change(?)</label><br/>
<input ng-model="my.name">
</form>
</body>
</html>
ng-repeat would be perfect for such cases. Not sure what makes you avoid that.
You can have a counter which will increment every time Name is added. Also pass same counter name as an argument for selectName function.
Every time selectName is called, argument value will be set as an model
Try this:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $compile) {
$scope.my = {
name: 'untitled'
};
var counter = 0;
$scope.add_Name = function(index) {
var myName = 'untitled' + counter;
var namehtml = '<label ng-click="selectName(\'' + myName + '\')">' + myName + ' //click<br/></label>';
var name = $compile(namehtml)($scope);
angular.element(document.getElementById('add')).append(name);
++counter;
};
$scope.selectName = function(val) {
$scope.my.name = val;
$scope.showName = true;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body ng-app="plunker" ng-controller="MainCtrl">
<button ng-click="add_Name($index)">Add Names</button>
<div id="add"></div>
<br/>
<form ng-show="showName">
<label>Name Change(?)</label>
<br/>
<input ng-model="my.name">
</form>
</body>
Working demo

how to bind names between text box to label

How can i bind values from shown single text box to label value ??
If i use ng-repeat in this i'm facing issues to my further functionalities.. can u pls solve this issue. i'm not able to bind between them ....Working DEMO
var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope, $compile) {
$scope.my = {name: 'untitled'};
var counter=0;
$scope.add_Name = function(index) {
var myName='untitled'+counter;
var namehtml = '<label ng-click="selectName(\''+myName+'\')">'+myName+' //click<br/></label>';
var name = $compile(namehtml)($scope);
angular.element(document.getElementById('add')).append(name);
++counter;
};
$scope.selectName = function(val) {
$scope.my.name=val;
$scope.showName = true;
};
});
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="add_Name($index)">Add Names</button>
<div id="add"></div><br/>
<form ng-show="showName">
<label>Name Change(?)</label><br/>
<input ng-model="my.name">
</form>
</body>
</html>
I have updated my code, here's a working version, finally i got the result:
var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope, $compile) {
$scope.my = {name: 'untitled'};
$scope.mies=[]; // added an array to store the generated values
var counter=0;
$scope.add_Name = function(index) {
$scope.mies[counter]={name: 'untitled'+counter}; // insert a new object into the array
var namehtml = '<label ng-click="selectName(mies[\''+counter+'\'])">{{mies['+counter+'].name}} //click<br/></label>';
var name = $compile(namehtml)($scope);
angular.element(document.getElementById('add')).append(name);
++counter;
};
$scope.selectName = function(val) {
$scope.my=val; // set my to val instead of my.name
$scope.showName = true;
};
});
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="add_Name($index)">Add Names</button>
<div id="add"></div><br/>
<form ng-show="showName">
<label>Name Change(?)</label><br/>
<input ng-model="my.name">
</form>
</body>
</html>

Categories