i've a simple problem, i've copied and pasted some code and i'd like to show an alert with a value inside it. I'm just learning angular and the fuction works (i've places a console log inside it and it is executed), but the window.alert doesn't appear.
I've read this tutorial and tried changing the name of variable but it's still not working. In the online tutorial of angual everything is going fine so where is my mistake?
Here is the page code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" charset="utf-8" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
<script type="text/javascript" charset="utf-8" src="greetings.js"></script>
</head>
<body>
<h1>Greetings</h1>
<div ng-app="greetings" ng-controller="GreetingsController as greeting">
<b>Greetings:</b>
<div>
Name: <input type="text" min="0" ng-model="greeting.name" required >
</div>
<div>
FamilyName: <input type="text" ng-model="greeting.familyName" required >
<select
data-ng-options="c for c in greeting.tipi" data-ng-model="greeting.selectedOption">
<!--<option ng-repeat="c in greeting.tipi">{{c}}</option>-->
</select>
</div>
<div>
<b>Greeting:</b>
<span>
{{greeting.total(greeting.selectedOption)}} {{greeting.name}} {{greeting.familyName}}
<button class="btn" ng-click="invoice.greet(greeting.selectedOption)">Greet</button>
<br/>
</span>
</div>
</div>
</body>
</html>
Here is the controller code greetings.js:
angular.module('greetings', [])
.controller('GreetingsController', function() {
this.name = "Name";
this.familyName = "FamilyName";
this.tipi = ["Hello", "Good Morning", "Good Afternoon", "Good evening"];
this.selectedOption = this.tipi[0];
this.total = function total(outGree) {
console.log(outGree);
return outGree;
};
this.greet = function greet(outGree) {
console.log(outGree);
$window.alert(outGree);
};
});
To use an Angular service, you add it as a dependency for the component (controller, service, filter or directive) that depends on the service.
And $window is a service.
you should add the parameter or the dependency $window to use this service.
angular.module('greetings', [])
.controller('GreetingsController', ['$window', function($window) {
this.name = "Name";
this.familyName = "FamilyName";
this.tipi = ["Hello", "Good Morning", "Good Afternoon", "Good evening"];
this.selectedOption = this.tipi[0];
this.total = function total(outGree) {
console.log(outGree);
return outGree;
};
this.greet = function greet(outGree) {
console.log(outGree);
$window.alert(outGree);
};
}]);
You need to include $window in your dependencies, or else your controller reads it as undefined.
Try the following:
angular.module('greetings', [])
.controller('GreetingsController', function($window) {
//Rest of your code
this.greet = function greet(outGree) {
console.log(outGree);
$window.alert(outGree);
};
});
I added $window as a parameter to the function of your controller.
the problem was in the html code:
<button class="btn" ng-click="invoice.greet(greeting.selectedOption)">Greet</button>
should have been:
<button class="btn" ng-click="greeting.greet(greeting.selectedOption)">Greet</button>
Related
I am working on a form having multiple radio button listings in which I will need to create dynamic ng-model for each of the radio button. I am being able to do that, but when same I am trying to retrieve in controller (USING the ng-model iteration with angular forEach loop) it seems model cannot be replicated with console.log. Anyone help?
HTML
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<p ng-repeat="x in dummy">
<input type="radio" name="{{x.name}}" id="{{x.id}}" ng-model="Ques[x.id]"><span>{{x.value}}</span>
</p>
<button ng-click="ok()">Click</button>
<script>
//module declaration
var app = angular.module("myApp",[]);
//controller
app.controller("myCtrl", function($scope){
$scope.dummy = [
{name:"name1",value:"red",id:"id1"},
{name:"name2",value:"blue",id:"id2"},
{name:"name3",value:"yellow",id:"id3"},
];
$scope.ok = function(){
angular.forEach($scope.dummy, function(val, key) {
console.log($scope.Ques.val.id);
});
}
});
</script>
</head>
</html>
The Angular model is a JavaScript object itself. Instead of looping through the object, you can output the entire object to the console like this:
console.log( JSON.stringify($scope.dummy) );
To make it more easy to read and span multiple lines for complex objects, just add these arguments to stringify:
console.log( JSON.stringify($scope.dummy, null, 2) );
It also looks like you need a little work on how you handle the Radio buttons, I'll leave that to the excellent odetocode blog/site:
http://odetocode.com/blogs/scott/archive/2013/06/25/radio-buttons-with-angularjs.aspx
The main problem is that you're inside ngRepeat and it creates a child $scope, so to make it work, you should use or the Dot Rule or controller-as-syntax, as below:
$scope.model = {};
Then in your view:
<label>
<input type="radio" id="{{x.id}}" value="{{x.value}}" ng-model="model.Ques[x.id]">{{x.value}}
</label>
See it working:
(function() {
'use strict';
angular
.module('myApp', [])
.controller("myCtrl", function($scope) {
$scope.dummy = [
{
"name":"name1",
"value":"red",
"id":"id1"
},
{
"name":"name2",
"value":"blue",
"id":"id2"
},
{
"name":"name3",
"value":"yellow",
"id":"id3"
}
];
$scope.model = {};
$scope.ok = function() {
// With your original code:
angular.forEach($scope.dummy, function(val, key) {
console.log($scope.model.Ques[val.id]); // <- note the syntax
});
// Or you can get all key / values stored in radio buttons:
/*for (var key in $scope.model.Ques) {
console.log('Key => ', key);
console.log('Value => ', $scope.model.Ques[key]);
}*/
}
});
})();
<!doctype html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<p ng-repeat="x in dummy">
<label>
<input type="radio" value="{{x.value}}" id="{{x.id}}" ng-model="model.Ques[x.id]">{{x.value}}
</label>
</p>
<button ng-click="ok()">Click</button>
</body>
</html>
For reference, check the #PankajParkar's answer.
Have a look at that.
<body ng-app="myApp" ng-controller="myCtrl">
<p ng-repeat="x in dummy">
<input type="checkbox" name="{{x.name}}" id="{{x.id}}" ng-model="Ques[x.id]" />
<label>{{x.name}}</label>
</p>
<button ng-click="ok()">Click</button>
<script>
//module declaration
var app = angular.module("myApp",[]);
//controller
app.controller("myCtrl", function($scope){
$scope.dummy = [
{name:"name1",value:"red",id:"id1"},
{name:"name2",value:"blue",id:"id2"},
{name:"name3",value:"yellow",id:"id3"},
];
$scope.Ques = {};
$scope.ok = function(){
angular.forEach($scope.dummy, function(val, key) {
console.log($scope.Ques[val.id]);
});
}
});
I have these files:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Gestore Anagrafica</title>
</head>
<body>
<div>
<h3>Insert new person</h3>
<div ng-app="Person" ng-controller="PersonController">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
Age: <input type="number" ng-model="age"><br>
<br>
Full Name: {{fullName()}} <br>
Is major: {{isMajor()}} <br>
<button ng-click="add()">Add Person</button>
</div>
</div>
<script type="text/javascript" src="js/angular.js"></script>
<script type="text/javascript" src="js/RegistryService.js"></script>
<script type="text/javascript" src="js/PersonController.js"></script>
</body>
</html>
js/RegistryService.js:
angular.module('RegistryService', []).
service('registry', function()
{
this.people = [];
this.add = function(person)
{
people.push(person);
}
});
js/PersonController.js:
var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController',['registry', function($scope, registry) {
$scope.firstName = "testName";
$scope.lastName = "";
$scope.age = 20;
$scope.isMajor = function()
{
return $scope.age > 18;
};
$scope.add = function()
{
registry.add({ 'firstName': $scope.firstName,
'lastName': $scope.lastName,
'age': $scope.age});
};
$scope.fullName = function()
{
return $scope.firstName + " " + $scope.lastName;
};
}]);
The binding does not occur: when i change the name or the age nothing happens, moreover in the beginning the input are all blank but i expect to see 20 in age and testName in firstName. The browser's console shows no error. Am i missing something?
Constraints: the service 'RegistryService' MUST be in another file.
Question:
with these two lines
var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController',['registry', function($scope, registry) {
i am telling that the module named Person needs something called RegistryService to work, the controller PersonController will use the 'registry' thing located into the RegistryService (hence if i put here something that is not defined into RegistryService is an error). function($scope, registry) is the constructor of the controller that uses a global variable $scope and the variable registry taken from 'RegistryService'. Is my overall understanding of the dependency injection good?
You need to describe $scope injection too, since you expect it to be available in your controller function as the first parameter:
var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController', ['$scope', 'registry', function($scope, registry) { }]);
You didn't inject $scope properly
app.controller('PersonController',['$scope', 'registry', function($scope, registry) {
I have a controller with such:
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
If next() (with ngClick) is called 3 times, we get:
//1
//2
//3
but if back() (with ngSwipeLeft) is called it returns
//-1
when I'm obviously expecting
//2
What am I missing here?
update: including ngTouch details - this seems to be the problem.. ngTouch is included.
When I watch the myVar value - its like it exists twice - one with the ngSwipeLeft call, and one with the ngClick call
Your snippet looks fine to me. You need to provide more code, error might be somewhere else. Look at the code below.
<!doctype html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-touch.min.js"></script>
<script>
var app = angular.module('myapp',['ngTouch']);
var controller = app.controller('mycontroller', ['$scope',function($scope){
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
}]);
</script>
</head>
<body ng-controller="mycontroller">
<div>
<h1>MyVar: {{myVar}}!</h1>
<input type="button" value="back" ng-click="back()"/>
<input type="button" value="next" ng-click="next()"/>
</div>
</body>
</html>
Ok, so I've figured out my problem - I wasn't providing enough detail in the question - but if someone runs into something similar in the future, heres what was going on:
I was declaring my controller with ng-controller="myCtrl" in the templates, but also using routing, where I declared my controller like:
$routeProvider.when('/', {
templateUrl: 'myUrl.html',
controller: 'myCtrl'
});
This was instantiating the controller twice, and obviously causing problems (although that seemed to the only one to surface for now).
Removing the controller definition from the routing or the view did the trick.
need to see your html not sure about your problem, here is a sample working code,
<div ng-app="myapp">
<div ng-controller="IncDecController">
<span>current value is {{myVar}}</span>
<img src="https://angularjs.org/img/AngularJS-large.png" ng-swipe-left="back()"></img>
<button ng-click="next()">next</button>
</div>
</div>
script:
angular.module('myapp', ['ngTouch'])
.controller('IncDecController', ['$scope', function ($scope) {
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
}])
I'm new to Angular JS. Sorry for this simple question.
I have learnt something from this tutorial: http://courseware.codeschool.com/shaping-up-with-angular-js/Slides/level01-05.pdf
And I have tried an example. This is not working. http://jsfiddle.net/89wfv/1/
HTML:
<html ng-app="main">
<body>
<div ng-controller="con">
<div>{{con.desc}}</div>
<input type='button' ng-click='getDesc();' value='Get name' />
</div>
</body>
</html>
Script
(function() {
var app = angular.module("main", []);
app.controller("con", function() {
this.desc = "test description";
this.getDesc = function() {
alert(this.desc);
}
});
})();
Problem is showing description in div and alert description by click.
Thanks in advance.
you forgot controller as something
<div ng-controller="con as ctrl">
<div>{{ctrl.desc}}</div>
<input type='button' ng-click='ctrl.getDesc();' value='Get name' />
</div>
take a look at the guide instead :
https://docs.angularjs.org/guide/controller
works:
http://jsfiddle.net/pYh89/
you didnt load angular correctly and add several syntax errors.
var app = angular.module("main", []);
app.controller("con", function () {
this.name = 'foo';
this.getName = function () {
alert("foo");
};
});
Angular JS is missing in your code please include it after downloading it.
<script src="angular.js"></script>
You can also use online version.
You forgot different things:
Here's a corrected JSfiddle:
http://jsfiddle.net/89wfv/2/
You have to:
Use $scope instead of this to reference to the data that is to be bound to the view, eg:
app.controller("con", function($scope) {
$scope.name = 'vasu';
$scope.getName = function() {
alert();
}
});
Put the script tag in Head
Not use the html tag, that could be overwritten by JSfiddle:
Do rather something like this:
<div ng-app="main">
<div ng-controller="con">
</div>
</div>
I'm trying to write a sample AngularJS, and SpringMVC project. The spring methods works fine, but I have a problem with declaraton of function in my site controller. My app should return a word from text input, but when I click the button, I've got this error:
[13:23:58.900] "Error: fnPtr is not a function
parser/_functionCall/<#http://localhost:8080/example/resources/js/Angular/angular.js:6542
ngEventDirectives[directiveName]</</</<#http://localhost:8080/example/resources/js/Angular/angular.js:13256
Scope.prototype.$eval#http://localhost:8080/example/resources/js/Angular/angular.js:8218
Scope.prototype.$apply#http://localhost:8080/example/resources/js/Angular/angular.js:8298
ngEventDirectives[directiveName]</</<#http://localhost:8080/example/resources/js/Angular/angular.js:13255
createEventHandler/eventHandler/<#http://localhost:8080/example/resources/js/Angular/angular.js:2095
forEach#http://localhost:8080/example/resources/js/Angular/angular.js:130
createEventHandler/eventHandler#http://localhost:8080/example/resources/js/Angular/angular.js:2094
"
This is my index.html:
<!DOCTYPE html>
<html lang="en" ng-app="Apken">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="resources/js/Angular/angular.js"></script>
<script src="resources/js/controler.js"></script>
</head>
<body ng-controller="theNamer">
<div class="input-append">
<input style="width:358px;" class="span2" type="text" ng-model="myName" required min="1" />
<button class="btn btn-primary" ng-disabled="!myName" ng-click="send()">Click!</button>
</div>
<ul>
<li ng-repeat="name in names">{{name}}</li>
</ul>
</body>
</html>
And controler.js:
function theNamer ($scope,$http){
$scope.myName='aa';
$scope.fetchList=new function()
{
$http.get('ca/list.json').success(function(thList){
$scope.names = thList;
});
}
$scope.send=new function()
{
$http.post('ca/set/3').success(function(){
$scope.fetchList;
});
}
$scope.fetchList;
}
var Apken = angular.module('Apken',[]);
Apken.controller('theNamer', theNamer);
I've noticed, that must be a some kind of problem with function declaration in the ng-click value. On site startup controler.js works fine, but it crashes, when I click the button.
Just wanted to add for anybody receiving this error, it can also be seen if you, like me, make the n00b mistake of creating a variable with the same name as function (the function being called from ng-click:
$scope.addTask = {};
$scope.addTask = function() {};
I have tested your code. Using AngularJS 1.0.7, the error disappears when you replace
$scope.send = new function() {
with
$scope.send = function () {
and same applies to fetchList.
I guess you mixed the two syntaxes function(*args*) { *body* } and new Function(*args*, *body*). Check on MDN: Function.
You have also to change your code in order to get your fetchList properly called:
function theNamer($scope, $http) {
$scope.myName = 'aa';
$scope.fetchList = function() {
$http.get('ca/list.json').success(function(thList) {
$scope.names = thList;
});
};
$scope.send = function() {
$http.post('ca/set/3').success(function() {
$scope.fetchList();
});
};
$scope.fetchList();
}