Basic function in AngularJS - javascript

I'm trying to write a simple "Hello World" application with AngularJS.
I would expect the function greeting() to print the name inserted in the text input in real time, but instead I get simply {{greeting()}} in output. What's wrong?
<!doctype html>
<body ng-app="myApp">
<div ng-controller="userController">
<p>Name: <input type="text" ng-model="user.name"></p>
<p>Surname: <input type="text" ng-model="user.surname"></p>
<p>{{greeting()}}</p>
</div>
<script type="text/javascript">
angular.module("myApp", [])
.controller("userController",
function ($scope) {
$scope.user = {name: "Mario", surname: "Rossi"};
$scope.greeting = function() {
return "Hello " +
$scope.user.name + " " +
$scope.user.surname + "!"
};
});
</script>
</body>
</html>
Here's an example: I would like to see Hello John Smith! instead of {{greeting()}}.

You forgot to include the AngularJS JavaScript.
Otherwise it works fine:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="userController">
<p>Name: <input type="text" ng-model="user.name"></p>
<p>Surname: <input type="text" ng-model="user.surname"></p>
<p>{{greeting()}}</p>
</div>
<script type="text/javascript">
angular.module("myApp", [])
.controller("userController",
function($scope) {
$scope.user = {
name: "Mario",
surname: "Rossi"
};
$scope.greeting = function() {
return "Hello " +
$scope.user.name + " " +
$scope.user.surname + "!"
};
});
</script>
</body>

Related

Custom service to display array in angularjs

Can anyone please explain to me how to create a custom service for displaying the array .the array is created inside the service and a function savedata() which saves the objects in the array.like wise another function i want to create which will display the array. thanks in advance
<!DOCTYPE html>
<html ng-app="noteApp">
<head>
<title>Note App</title>
<script src="angular.js"></script>
</head>
<body>
<div ng-controller="noteCtrl">
<form name="noteForm">
NoteId: <input type="number" name="id" ng-model="note.id" required>
NoteTitle: <input type="text" name="title" ng-model="note.title" required>
NoteDiscription: <input type="text" name="discription" ng-model="note.discription" required><br><br>
<button ng-click="add()" ng-disabled="noteForm.$invalid">Click</button>
</form>
<div ng-repeat="number in noteArray track by $index">
<h3>{{::number.id}}</h3>
<h3>{{::number.title}}</h3>
<h3 >{{::number.discription}}</h3>
</div>
</div>
<script>
var app=angular.module('noteApp',[]);
app.service('dataService',function(){
var noteArray=[];
this.saveData=function(data){
console.log(noteArray);
return noteArray.push(data);
}
this.displayData=function(){
//return zz;
}
});
app.controller('noteCtrl',function($scope,dataService) {
$scope.add=function(){
dataService.saveData($scope.note);
//dataService.displayData();
}
});
</script>
</body>
</html>
You are on the right track, just return the array inside the displayData()
this.displayData=function(){
return noteArray;
}
DEMO
var app=angular.module('noteApp',[]);
app.service('dataService',function(){
var noteArray=[];
this.saveData=function(data){
console.log(noteArray);
return noteArray.push(data);
}
this.displayData=function(){
return noteArray;
}
});
app.controller('noteCtrl',function($scope,dataService) {
$scope.noteArray=[];
$scope.add=function(){
dataService.saveData($scope.note);
$scope.noteArray = dataService.displayData();
}
});
<html ng-app="noteApp">
<head>
<title>Note App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="noteCtrl">
<form name="noteForm">
NoteId: <input type="number" name="id" ng-model="note.id" required><br><br>
NoteTitle: <input type="text" name="title" ng-model="note.title" required>
<br><br>
NoteDiscription: <input type="text" name="discription" ng-
model="note.discription" required><br><br>
<button ng-click="add()" >Click</button>
</form>
<div ng-repeat="number in noteArray track by $index">
<h3 >{{number.id}}</h3>
<h3 >{{number.title}}</h3>
<h3 >{{number.discription}}</h3>
</div>
</div>
</body>
</html>
Well I think that you need some like that:
'use strict';
app.factory('$shared',[function(){
function foo() {
var self = this;
self.list = [];
}
return new foo();
}]);
app.controller('mainCtrl', ['$scope', '$shared', function($scope, $shared){
$scope.shared = $shared;
//... many things here
$scope.onClick = function() {
// be sure that, I use "shared" from $scope, no directly like "$shared"
$scope.shared.list.push("val1");
console.log("my shared array:", $scope.shared.list);
}
}]);
app.controller('secondCtrl', ['$scope', '$shared', function($scope, $shared){
$scope.shared = $shared;
//... many things here
$scope.onKeyPress = function() {
// be sure that, I use "shared" from $scope, no directly like "$shared"
$scope.shared.list.push("val2");
console.log("my shared array:", $scope.shared.list);
}
}]);

Info from loadData in JavaScript is not appearing in my html

I have a form that should submit a request to the open movie database and return the movies. But it isn't returning anything and it seems as though loadData isn't even working. Because $greeting.text('So, you want to search for ' + movieStr); isn't working either. It should show So you want to search for in the html and it doesn't appear. If go directly to www.omdbapi.com/?t=fall it returns a json.
function loadData(){
var $movieElem = $('movie-items');
var $greeting = $('#greeting');
$movieElem.text("");
var movieStr = $('#movie').val();
var omdbapiUrl = 'www.omdbapi.com/?t='+ movieStr;
$greeting.text('So, you want to search for ' + movieStr);
$.getJSON(omdbapiUrl, function(data){
items = data.response.docs;
for (var i=0; i < items.length; i++){
var item = items[i];
$movieElem.append('<li>'+ '<p>' + item.Title + '<p>' +'<p>' + item.Director + '</p>'+'</li>');
};
}).error(function(e)){
});
$('#form-container').submit(loadData);
}
<form id="form-container" class="form-container">
<label for="movie">Movie:</label><input type="text" id="movie" value=""><br>
<button id="submit-btn">Submit</button>
</form>
<h2 id="greeting">What do you want to search for? </h2>
<ul id="movie-items"> Movie info will appear here</ul>
Thanks for the suggestion. I modified my code and it still isn't showing anything. I think the primary issue is that loadData isn't being called because nothing is appearing in the console.log when I added a console.log statement from within loadData. Is there something wrong with this line that is loading the data? I don't see any errors in the console.log
$('#form-container').submit(loadData);
This is from the html
<form id="form-container" class="form-container">
This isn't showing anything in the console.log
console.log("Hello from loadData");
This is script.js
function loadData(){
console.log("Hello from loadData");
var $movieElem = $('movie-items');
var $greeting = $('#greeting');
$movieElem.text("");
var movieStr = $('#movie').val();
$greeting.text('So, you want to search for ' + movieStr);
var omdbapiUrl = 'http://www.omdbapi.com/?t=fall';
$(document).ready(function () {
$.getJSON(omdbapiUrl, function(data){
console.log(data);
}).error(function(e){
});
});
$('#form-container').submit(loadData);
}
This is the html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form-container" class="form-container">
<label for="movie">Movie:</label><input type="text" id="movie" value=""><br>
<button id="submit-btn">Submit</button>
</form>
<h2 id="greeting">What do you want to search for? </h2>
<ul id="movie-items"> Movie info will appear here</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
<script src="js/script.js"></script>
</body>
</html>
Us the example bellow. You are adding an extra parenthesis and you are missing the http: for external calls
the problem: .error(function(e)){
$(document).ready(function() {
function loadData(e) {
e.preventDefault();
console.log("Hello from loadData");
var $movieElem = $('movie-items');
var $greeting = $('#greeting');
$movieElem.text("");
var movieStr = $('#movie').val();
$greeting.text('So, you want to search for ' + movieStr);
var omdbapiUrl = 'http://www.omdbapi.com/?t=fall';
$.getJSON(omdbapiUrl, function(data) {
console.log(data);
}).error(function(e) {
});
}
$('#form-container').submit(loadData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form-container" class="form-container">
<label for="movie">Movie:</label><input type="text" id="movie" value=""><br>
<button id="submit-btn">Submit</button>
</form>
<h2 id="greeting">What do you want to search for? </h2>
<ul id="movie-items"> Movie info will appear here</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
<script src="js/script.js"></script>
</body>
</html>
The solution was to remove all the extra stuff in my script.js file that wasn't needed and wasn't being called and just leave Panagiotis Vrs's code.
var omdbapiUrl = 'http://www.omdbapi.com/?t=fall';
$(document).ready(function () {
$.getJSON(omdbapiUrl, function(data){
console.log(data);
}).error(function(e){
});
});
EDIT:
I have used Panagiotis Vr's code to instead wrap everything in a document.ready as mentioned in the below post.

ng-controller Angular capitalize input

I want the first typed letter turn into a capital letter, but struggeling with Angular. Maybe it is a little detail that I missed out, so a fresh eye to look at this would be helpful.
var app = angular.module("todoApp", []);
app.filter("NameInput", function(){
return function(input, scope){
if (input!=null)
input = input.toLowerCase();
return input.substring(0,1).toUpperCase()+input.substring(1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body ng-app="todoApp" ng-cloak>
<div id="wrapper">
<div ng-controller="NameInput">
<label>Name:</label>
<input id="name-input" type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}</h1>
</div>
</div>
</body>
Here you go...
I think this might help you
var app = angular.module("todoApp", []);
app.filter("NameInput", function() {
return function(input) {
if (input != null) {
input = input.toLowerCase();
return input.substring(0, 1).toUpperCase() + input.substring(1);
}
}
})
.controller('NameInput', function($scope) {
$scope.yourName = "";
});
<body ng-app="todoApp" ng-cloak>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div id="wrapper">
<div ng-controller="NameInput">
<label>Name:</label>
<input id="name-input" type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName | NameInput}}</h1>
</div>
</div>
</body>

Angular JS - nesting templates (double curly brackets {{}} )

Is there a way to nest angular templates?
for example having the following variables:
$scope.myVar = 'hello {{name}}, you weigh {{weight}}'
$scope.name = '';
$scope.weight = '';
And having the html file looking something like:
<h1>{{myVar}}</h1>
<div>
Your Name:
<input ng-model="name" type="text">
</div>
<div>
Your Weight:
<input ng-model="weight" type="text">
</div>
And then have angular dynamically setting the name and weight template from myVar?
I think that you are looking for is meaningless. You could define a function like below and then call this function in the header.
$scope.myVar = function() {
return 'hello ' + $scope.name + ' you weigh '+ $scope.weight;
}
var app = angular.module('app',[]);
app.controller('mainController',['$scope', function($scope){
$scope.name = "test";
$scope.weight = 100;
$scope.myVar = function() { return 'hello ' + $scope.name + ' you weigh ' + $scope.weight; };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<head>
</head>
<body ng-app="app">
<div ng-controller="mainController">
<h1>{{myVar()}}</h1>
<div>
Your Name:
<input ng-model="name" type="text"/>
</div>
<br/>
<div>
Your Weight:
<input ng-model="weight" type="text"/>
</div>
</div>
</body>
</html>
I ended up realizing that I had scoping errors. So, to solve the binding errors, I used $interpolate. See: How to evaluate angularjs expression inside another expression
Sure you would just do:
<h1>Hello {{name}} you weigh {{weight}}</h1>
<div>
Your Name:
<input ng-model="name" type="text">
</div>
<div>
Your Weight:
<input ng-model="weight" type="text">
</div>

I Can't get the most simple knockout.js sample to work?

I have tried this code but this not working properly. my code is below
<link href="~/Content/knocktest.css" rel="stylesheet" />
<script src="~/Scripts/knockout-2.3.0.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var ViewModel = function (first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function () {
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth"));
});
</script>
my html code below
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
You have no errors in your code, so really the only thing that you are missing is your reference to the jQuery library since you are using;
$(document).ready(function () {
// rest of your code here
});
If you don't include jQuery then you can just remove the $(document).ready() code, and make sure that your JavaScript is after all of your html elements within the body.
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<span data-bind="text: firstName"></span>
<span data-bind="text: lastName"></span>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.1/knockout-min.js"> </script>
<script>
var ViewModel = function (first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function () {
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth"));
</script>
Please check out this demo of your code at jsbin

Categories

Resources