Creating a multiplication function in an angularjs controller? - javascript

I am trying to create a multiplication function in an angularjs controller. I want the function to return the product of quantity and price. I'm using the snippet below, but it's returning an error. What am I doing wrong?
<!DOCTYPE html> <html>
<head> <script src= "Angular.js"></script> </head>
<body>
<div ng-app="" ng-controller="personController">
<h2>Cost Calculator</h2>
Quantity: <input type="number" ng-model="quantity"> Price: <input type="number" ng-model="price">
<p><b>Total in dollar:</b> {{fullname()}}</p>
</div>
<script> function personController(scope) { var input1 = scope.quantity , var input2 = scope.price ,
$scope.fullName = function() {
return {{input1 * input2}};
} } </script>
</body> </html>

In this simple example you do not need to create a controller.
See here
<h2>Cost Calculator</h2>
Quantity:
<input type="number" ng-model="quantity">Price:
<input type="number" ng-model="price">
<p><b>Total in dollar:</b> {{quantity*price}}</p>
</div>
But, if you need create it - see mistakes:
angulars interpolation syntax {{ }} is only used in HTML, not javascript.
Use $scope, not scope
formatting your code is important.

Here is an example using the currency filter. You might also want to take a look at the number filter.
Note: Starting in angular 1.3.0 the currency filter lets you add a fractionSize.
angular.module('myApp',[])
.controller('personController', ['$scope', function($scope) {
$scope.price = 0;
$scope.quantity = 0;
$scope.total = function() {
return $scope.price * $scope.quantity;
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="personController">
<h2>Cost Calculator</h2>
Quantity: <input type="number" ng-model="quantity">
Price: <input type="number" ng-model="price">
<p><b>Total in dollars:</b> {{ total() | currency : $ }}</p>
</div>

<script> function personController(scope) {
var input1 = scope.quantity;,
var input2 = scope.price;
$scope.fullName = function() {
return {{input1 * input2}};
}
}
</script>
</body> </html>
There is a clear syntax error here which is {{input * input2}}. This is angularjs expression syntax, not javascript syntax. Try just using input * input2. You are also referring to $scope which is not available, so change to 'scope':
scope.fullName = function() {
return input1 * input2;
}
Or, you could refer to the scope variables directly
scope.fullName = function() {
return scope.quantity * scope.price;
}
Or you could refer to them directly in the template:
<!DOCTYPE html> <html>
<head> <script src= "Angular.js"></script> </head>
<body>
<div ng-app="">
<h2>Cost Calculator</h2>
Quantity: <input type="number" ng-model="quantity"> Price: <input type="number" ng-model="price">
<p><b>Total in dollar:</b> {{quantity * price}}</p>
</div>
</body> </html>

you are not using $scope? thats not local variable that is injected $scope so name cannot be changes as we do with the argument names of loval variables
There were syntax errors as well i have refactored your code
Working demo
angular.module('test',[]).controller('personController', function ($scope) {
$scope.price = 0;
$scope.quantity=0
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html> <html>
<head> <script src= "Angular.js"></script> </head>
<body>
<div ng-app="test" ng-controller="personController">
<h2>Cost Calculator</h2>
Quantity: <input type="number" ng-model="quantity"> Price: <input type="number" ng-model="price">
<p><b>Total in dollar:</b> {{quantity*price}}</p>
</div>
</body> </html>

Related

How to use replace function with Angular?

I am trying to do a simple two way binding but checking and updating the input text if it contains two word strings. For example if the input is "Comedy Movies" then
Comedy Movies ----> comedy_movies
I did this through jQuery like
var str = $('#item').val()
if (str.match(/^[a-z\.]+ [a-z]+/i)) {
str = str.replace(/\s+/g, '_').toLowerCase();
}
But not sure how to do it through angular. How can I fix this?
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app>
Item:
<input type="text" ng-model="name" id="item"/>
<br />
<br />
<div>{{name}}</div>
</div>
You can bind using ng-bind of a function that contains you code - see a demo below:
angular.module('app', []).controller('ctrl', function($scope) {
$scope.name = 'Comedy Movies';
$scope.getString = function() {
var str = $scope.name;
if (str.match(/^[a-z\.]+ [a-z]+/i)) {
str = str.replace(/\s+/g, '_').toLowerCase();
}
return str;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
Item:
<input type="text" ng-model="name" id="item" />
<br />
<br />
<div ng-bind="getString()"></div>
</div>

Use data from localStorage in HTML

By using the advanced settings page.
And I try, depending on the selected radiobatton change the name of the units (units themselves vary in the query (!)).
Example:
$scope.savecity=function(){
localStorage["var"]=$scope.username;
localStorage["SystemOfNumbers"]=$scope.SystemOfNumbers;
<label>
<input type="radio" ng-model="SystemOfNumbers" value="metric">
Metric
</label>
<label>
<input type="radio" ng-model="SystemOfNumbers" value="imperial">
Imperial
</label><br/>
<button ng-click='savecity()'>Submit</button>
$scope.savecity=function(){
localStorage["var"]=$scope.username;
localStorage["SystemOfNumbers"]=$scope.SystemOfNumbers;
if (localStorage[SystemOfNumbers]="metrical"){
localStorage["icon"]="°C"
}
else {
localStorage["icon"]="°F"
}
}
And popup.html:
{{vm.data.list[0].temp.day}}{{localStorage["icon"]}}
That is, the selector is activated, changing the way of translation, but does not change the display unit.
Source: http://zalil.su/9855055
Answer:
You can enter city name on options page (but onle English)
(function(angular) {
'use strict';
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
$scope.username = '';
$scope.sayHello = function() {
$scope.greeting = 'Hello ' + $scope.username + '!';
};
$scope.savecity=function(){
localStorage["var"]=$scope.username;
localStorage["SystemOfNumbers"]=$scope.SystemOfNumbers;
};
}]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
-<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Angular JS</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="angular.min.js"></script>
<script src="weather 2.js"></script>
</head>
<body ng-app="scopeExample">
<div ng-controller="MyController">
Enter city name:
<input type="text" ng-model="username">
<label>
<input type="radio" ng-model="SystemOfNumbers" value="metric">
Metric
</label>
<label>
<input type="radio" ng-model="SystemOfNumbers" value="imperial">
Imperial
</label><br/>
<button ng-click='savecity()'>greet</button>
Назад
</div>
</body>
</html>

Error in AngularJS script output

I'm new to AngJS and I'm trying to write code on my own. I got stuck in one part.
Code:
<!DOCTYPE HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<title> First page </title>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="person.firstName"> <br>
Last Name: <input type="text" ng-model="person.lastName"> <br>
<p> {{person.firstName + " " + person.lastName}} age is: {{age[0]}}</p>
</div>
<div ng-app="mApp" ng-controller="mCtrl">
Registration number: <input type="number" ng-model="person.regNum"> <br>
Class number: <input type="text" ng-model="person.classNum"> <br>
<p> {{person.regNum, person.classNum}} </p>
</div>
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope) {
$scope.person = {firstName:"Nikhil",lastName:"Hegde"};
$scope.age = [20,21,22];
});
var app1 = angular.module('mApp',[]);
app1.controller('mCtrl',function($scope) {
$scope.person = {regNum:"122503",classNum:"12EC48"};
});
</script>
</body>
</html>
I'm not really sure what is wrong with the second pair of fields but the output as you can see is incorrect.
Also can I reuse the app variable?
app = angular.module('myApp',[]);
Instead of using a separate 'app1' variable, can I also reuse the same variable 'app' as:
app = angular.module('mApp',[]);
You should have only one app
<!DOCTYPE HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<title> First page </title>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
First Name: <input type="text" ng-model="person.firstName"> <br>
Last Name: <input type="text" ng-model="person.lastName"> <br>
<p> {{person.firstName + " " + person.lastName}} age is: {{age[0]}}</p>
</div>
<div ng-controller="mCtrl">
Registration number: <input type="number" ng-model="person.regNum"> <br>
Class number: <input type="text" ng-model="person.classNum"> <br>
<p> {{person.regNum, person.classNum}} </p>
</div>
<script>
var app = angular.module('myApp',[])
.controller('myCtrl',function($scope) {
$scope.person = {firstName:"Nikhil",lastName:"Hegde"};
$scope.age = [20,21,22];
})
.controller('mCtrl',function($scope) {
$scope.person = {regNum:"122503",classNum:"12EC48"};
});
</script>
</body>
</html>
<body>
<div ng-app="myApp">
<div ng-controller="myCtrl">
First Name: <input type="text" ng-model="person.firstName"> <br>
Last Name: <input type="text" ng-model="person.lastName"> <br>
<p> {{person.firstName + " " + person.lastName}} age is: {{age[0]}}</p>
</div>
<div ng-controller="mCtrl">
Registration number: <input type="number" ng-model="person.regNum"> <br>
Class number: <input type="text" ng-model="person.classNum"> <br>
<p> {{person.regNum+ " "+ person.classNum}} </p>
</div>
</div>
Script file
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope) {
$scope.person = {'firstName':"Nikhil",'lastName':"Hegde"};
$scope.age = [20,21,22];
});
app.controller('mCtrl',function($scope) {
$scope.person1 = {'regNum':"122503",'classNum':"12EC48"};
});
define your app only once. You can add multiple controller to ng-module.
Hope It will be useful.
You can have only 1 module in an app, have different scope variable inside same controller
var app = angular.module('myApp', []);
app.controller("myCtrl", ["$scope", "$http",
function($scope, $http) {
$scope.person = {
firstName: "Nikhil",
lastName: "Hegde"
};
$scope.registration = {
regNum: "122503",
classNum: "12EC48"
};
$scope.age = [20, 21, 22];
}
]);
DEMO

Unable to send parameters to ng-init

<input type="number" maxlength="1" max="5" min="0" placeholder="0" ng-model="rate">
<div ng-init="stars=Func(2)">
Rating: <span ng-repeat="x in stars track by $index">*</span>
</div>
In the above code I want to pass ng-model="rate", rate to the function Func.
ex: Func(rate); here rate should pass from ng-model.
JS Code:
var val='';
$scope.Func = function fun(n){
if(n == 0){
val = val + '';
} else {
val = val+'a';
return fun(n-1);
} return val;
};
You would need to rewrite your Func, such that it returns an array that contains the number of elements of your rate, so that your ng-repeat can use it for the displaying of stars.
It is as easy as
$scope.Func = function(n) {
return new Array(n);
}
Now, use your ng-init to initialize your rate to two:
<input type="number" maxlength="1" max="5" min="0" placeholder="0" ng-model="rate" ng-init="rate=2" >
Plnkr here
Edit: If your requirement is not to use Array aka collection, then ng-repeat is out of option. Fear not, we can return a string of stars instead.
Change your Func to this:
$scope.getStars = function(n) {
var stars = "";
for (var i = 0; i < n; i++) {
stars += "*";
}
return stars;
}
And your rating will now just display the string:
<div >
Rating: {{getStars(rate)}}
</div>
New Plnkr here
Since you can't use arrays and your rate limite is considerably low, you don't need to make a function and you can use ngSwitch to show/hide the appropriate rate, as follows:
(function() {
'use strict';
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.rate = 2;
})
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<input type="number" maxlength="1" max="5" min="0" placeholder="0" ng-model="rate">
<div ng-switch="rate">
Rating:
<span ng-switch-when="1">*</span>
<span ng-switch-when="2">**</span>
<span ng-switch-when="3">***</span>
<span ng-switch-when="4">****</span>
<span ng-switch-when="5">*****</span>
</div>
</body>
</html>

How to Change each Appended text Angularjs

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>
If I understand what you're looking for correctly this should work.
HTML:
<body ng-controller="AddCtrl">
<button ng-click="add_Name()">Add Names</button>
<div ng-repeat="item in names">
<label ng-click="selectName($index)">{{$index}}- {{item}} //click to change<br/></label>
</div>
<form ng-show="showName">
<label>Name Change at index {{nameIndex}}</label><br/>
<input ng-model="names[nameIndex]">
</form>
</body>
JS:
$scope.names = [];
$scope.add_Name = function(index){
$scope.names.push('untitled')
}
$scope.selectName = function (index) {
$scope.nameIndex = index;
$scope.showName = true;
};

Categories