There are no errors or warnings. This function doesn't display the result, instead it shows as:
{{student.fullName}}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sample</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app = "mainApp" ng-controller="studentController">
Enter first name: <input type = "text" ng-model = "student.firstName"><br><br>
Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>
your full name is: {{student.fullName()}}
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Narasimha",
lastName: "Rao",
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>
</body>
</html>
output:
Works like a charm
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Narasimha",
lastName: "Rao",
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "mainApp" ng-controller="studentController">
Enter first name: <input type = "text" ng-model = "student.firstName"><br><br>
Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>
your full name is: {{student.fullName()}}
</div>
The code is working properly. What are you using to run your file?
Related
I am new to HTML and Javascript. I am trying to display feedback on my form, so when a user types a matching password and username to what I have in my UserList object, it returns "login successfull" but I cant get this to work.
Heres a plunker if you want to see it in action: https://plnkr.co/plunk/SRS21GqLPAVgA5JU
Heres my code:
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', '$http', function($scope, $http){
$scope.test = "Test Successful!";
$scope.target = 'https://happybuildings.sim.vuw.ac.nz/api/brownsol/user_list.json'
// retrieves userList JSON file from server
$http.get($scope.target)
.then(function successCall(response){
$scope.output = "Successfully retrieved userList from the server"
$scope.userList = response.data.users;
},
function errorCall(response){
$scope.output = "Error retrieving userList from the server "
$scope.output += " - ErrorCode = "
$scope.output += response.status;
});
$scope.loginValidator = function() {
for(var i = 0; i < userList.length; i++) {
if ($scope.usernameInput == userList[i].LoginName && $scope.passwordInput == userList[i].Password) {
$scope.feedback = 'Login Successful';
return true;
};
};
$scope.feedback = 'Login Failed';
};
}]);
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8"/>
<link rel="stylesheet" href="style.css">
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>{{test}}</p>
<p>{{output}}</p>
<p>{{userList}}</p>
<div>
<form>
log in
<input type = "text" placeholder = "username" ng-model = "usernameInput"></input>
<input type = "password" placeholder = "password" ng-model = "passwordInput"></input>
<button type = "submit" placeholder = "login" ng-click = "loginValidator()">login</button>
<p>{{feedback}}</p>
</form>
</div>
<p>the first username: {{userList[0].LoginName}}</p>
<p>the first password: {{userList[0].Password}}</p>
</body>
</html>
Typo in function $scope.loginValidator. Instead of $scope.userList, You have used userList Which is not defined. Check console for error.
$scope.loginValidator = function() {
for(var i = 0; i < $scope.userList.length; i++) {
if ($scope.usernameInput == $scope.userList[i].LoginName && $scope.passwordInput == $scope.userList[i].Password) {
$scope.feedback = 'Login Successful';
return true;
};
};
i am fetching some data from the server and based on that i am initialising the ng-value of input which is shown after the data is fetched. But after that when I call a function with ng-change, console log doesn't show the changed value of the ng-model="chosedOption". It continues to print "Paytm Blance" even after selecting other radio buttons.
angular js file
var app = angular.module("formModule", []);
var formController = ($scope, $http) => {
$scope.chosedOption = "Paytm Balance";
$scope.amount = 10;
$scope.resJson = "";
$scope.payOptions = undefined;
$scope.proceed = (chosedOption) => {
console.log(chosedOption);
console.log($scope.chosedOption);
}
$scope.loadDoc = () => {
const orderId = Math.floor(Math.random() * 10000) + 100000;
const data = {
amount: $scope.amount,
orderId: orderId
}
$http.post("http://localhost:3200/intiate_transaction_api",data)
.then(response => {
$scope.resJson = JSON.stringify(response, undefined, 4);
console.log(response);
let data = {
txnToken: response.data.body.txnToken,
orderId: orderId
}
$http.post('http://localhost:3200/fetch_payment_option_api', data)
.then(response2 => {
$scope.resJson = JSON.stringify(response2, undefined, 4);
$scope.payOptions = response2.data.body.merchantPayOption.paymentModes;
})
})
}
}
app.controller("formController", formController);
app.filter('safeHtml', $sce => {
return function(val) {
return $sce.trustAsHtml(val);
}
})
html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./style.css">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script>
<title>UI</title>
</head>
<body ng-app="formModule" ng-controller="formController">
<div class="result">
<div class="container">
<form name="amt" action="#"></form>
total amount<input type="text" id="amount" ng-model="amount" name="amount">
<button ng-click="loadDoc()">Pay</button>
</div>
</div>
<div id="payOtions" ng-if="payOptions">
<div ng-repeat="option in payOptions">
<label>
<div class="paymentOption" ng-class="">
<input name="payOption"
ng-change="proceed(option.displayName)"
ng-model="chosedOption" type="radio"
ng-value="option.displayName">
{{option.displayName}}
</div>
</label>
</div>
</div>
<pre><code id="demo" ng-bind-html="resJson | safeHtml"></code></pre>
<script src="./angularScript.js"></script>
</body>
</html>
output
can be checked here
The ng-change directive only listens to changes made by the user. It does not listen to changes made by the controller.
Any changes done by the controller should call the listening function from the controller.
I am new to Angular and following a tutorial to learn the basics. Below is the code that I have so far. It has a controller and a view
// Code goes here
(function() {
var app = angular.module("myApp", []);
var MainController = function($scope) {
var person = {
var firstName = "AAA",
var lastName = "BBB",
};
$scope.person = person;
$scope.message = "Hello";
}
app.controller("MainController", MainController);
}());
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angular.js#1.3.19" data-semver="1.3.19" src="https://code.angularjs.org/1.3.19/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="MainController">
<div>First Name: {{person.firstName}} </div>
</div>
</body>
</html>
It gives me the below error in console
Please let me know what I am doing incorrectly. Thanks!
The problem is in initializing person object:
var person = {
var firstName = "AAA",
var lastName = "BBB",
};
The right way to do that is:
var person = {
firstName: 'AAA',
lastName: 'BBB'
}
Hope, my answer will help you.
Thanks. : )
I wanna make a code that has nice structural like this:
https://github.com/nolimits4web/Swiper/blob/master/dist/js/swiper.jquery.js#L67
So, I made this. but it doesn't works.
http://jsbin.com/xiralokola/edit?html,js,output
// friends.js
$(function () {
'use strict';
function Friends() {
var settings = {
name: null,
age: null,
gender: null,
printTarget: null
};
}
Friends.prototype = {
getInfo: function () {
var subject = (this.gender == 'female') ? 'She' : 'He',
html = '<p>';
html += '\'' + this.name + '\' is my friend.';
html += subject + ' is' + this.age + ' years old.';
html += '</p>';
this.printTarget.append(html);
return html;
}
};
window.Friends = Friends;
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Friends</title>
</head>
<body>
<h1>Friends</h1>
<div id="print"></div>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="friends.js"></script>
<script>
var myFriend = new Friends({
name: 'Hee-sook',
age: 15,
gender: 'female',
printTarget: $('#print')
});
</script>
</body>
</html>
I think there are problems near the 'var settings'.
But I don't know how to fix it.
Please help me.
try this
you had 3 issues:
you've tried to call an instance of Friends before it was defined ($(function) should be on the html in that case and not on the js file)
should be:
<script>
$(function () {
var myFriend = new Friends({
name: 'Hee-sook',
age: 15,
gender: 'female',
printTarget: $('#print')
});
});
you didn't pass the settings object to the constructor, should be:
function Friends(settings) {
$.extend(this,settings);
}
you didn't call the getInfo() on the instance:
myFriend.getInfo();
I am getting the following error: Error: [$sce:itype] Attempted to trust a non-string value in a content requiring a string: Context: html on this simple code despite its typeof() saying it is a string...
var app = angular.module('app', ['angular.filter', 'ngSanitize']);
app.controller('MainCtrl', ['$scope', '$filter', function($scope, $filter) {
$scope.filters = {};
this.people = [{
name: 'Yasuhito Endo'
}, {
name: 'Dejan Damjanović'
}, {
name: 'Gao Lin'
}, {
name: 'Mohammed Noor'
}];
this.applyFilter = function() {
console.log('Making first names bold...');
this.people = $filter('nameBold')(this.people);
}
}]);
app.filter('nameBold', function($sce) {
return function(items) {
var filtered = [];
angular.forEach(items, function(item) {
var splitIt = item.name.split(" ");
item.name = '<strong>' + splitIt[0] + '</strong> ' + splitIt[1];
console.log('Trusting... ' + typeof(item.name));
// Trusting... string (4x) |
// OUTPUT ------------------
// It outputs as a string yet it gives me the error:
// Error: [$sce:itype] Attempted to trust a non-string value
// in a content requiring a string: Context: html
// --------------------------------
// https://docs.angularjs.org/error/$sce/itype?p0=html
filtered.push(item.name);
});
return $sce.trustAsHtml(filtered);
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script data-require="angular-filter#*" data-semver="0.5.2" src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.2/angular-filter.js"></script>
<script data-require="lodash.js#*" data-semver="3.10.0" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-sanitize.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as viewmodel">
<button ng-click="viewmodel.applyFilter()">Apply the Filter</button>
<div ng-repeat="person in viewmodel.people">
Person: <span ng-bind-html="person.name"></span>
</div>
</body>
</html>
Plunker snippet: http://plnkr.co/edit/rIlETpJ3GeW0YYqrc8NB?p=preview
As you can see from the code, it looks very simple yet the returned item is a string and yet it gives me that big, nasty error.
How do I fix this?
Thanks.
I figured it out. Just take what you put as variable (From object) and put it as as new variable to a string.
app.filter('nameBold', function($sce) {
return function(items) {
var filtered = [];
var itemName = "";
angular.forEach(items, function(item) {
var splitIt = item.name.split(" ");
item.name = '<strong>'+splitIt[0]+'</strong>';
itemName = item.name;
filtered.push(item.name);
});
return $sce.trustAsHtml(itemName);
};
});