Call the output of a function in a controller - angularjs

I have a function that runs in my html code and I'm having trouble calling that function to do more things with the output in the controller.
To start off with, here is my JS:
(function(angular) {
'use strict';
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $log) {
$scope.$log = $log;
$scope.disc = 'Enter Code';
$scope.pricetotal = 14;
$scope.discount = [{
"amt": 5,
"name": "12345",
"percent": 0
}, {
"amt": 0,
"name": "23456",
"percent": 5
}];
var output = function() {
var discountedprice = $scope.pricetotal;
angular.forEach($scope.discount, function(item) {
var discountname = item.name;
if (discountname === $scope.disc) {
discountedprice = ((100 - parseInt(item.percent)) / 100 * parseInt($scope.pricetotal)) - parseInt(item.amt);
}
});
return discountedprice;
};
$scope.discprice = output;
});
})(window.angular);
My HTML is below:
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div style="border:1px solid #eee; border-bottom:3px solid #ececec; padding:20px;">
<span><b>Add Code</b></span>
<br />
<div id="addDiscountCode">
<form name="frmDiscountForm" ng-submit="submit(discountModel)" id="frmDiscountForm" novalidate>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="name" style="font-weight:normal;">Name:</label>
<input type="text" id="name" name="Name" ng-model="disc" ng-minlength="1" ng-maxlength="20" maxlength="20" required class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<button type="submit" ng-click="$log.log(disc)" class=" form-control btn btn-primary">Enter</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div style="margin-left:25px;">
<span><b>Total before discount = </b></span>
{{pricetotal | currency}}<br/>
<span><b>Total after discount = </b></span>
{{ discprice() | currency }}
</div>
</div>
</div>
<br />
</body>
</html>
The issue I'm facing is when I call $scope.discprice() in the controller, it gives me an undefined output. Any tips with this would be appreciated.
Here's a plunker of my code:
http://plnkr.co/edit/bLqAdpGOwMsNThK3Ei6s?p=preview

As of my knowledge you can bind only model elements ,not variable,the best way put your return value as a model element and load the function as default and map the model element for binding

Related

Fetching user data using ng-click

Here is the list of users. I need to display particular user details when clicked on him.
<head>
<script>
(function() {
angular.module("testApp", ['ui.bootstrap']).controller('testCtrl', ['$scope', '$http', function($scope, $http) {
$scope.userData = undefined;
$http.get('https://randomuser.me/api/?results=30&nat=US').then(function(response) {
$scope.userData = response.data;
});
}]);
}());
</script>
<style></style>
</head>
<body ng-app="testApp">
<div ng-controller="testCtrl">
<h1> PERSONS</h1>
<form name="commonForm">
<div class="col-sm-4" ng-repeat="user in userData.results" ng-class="{active : isSelected(user)} style="margin-top:50px;">
<img class="col-sm-4" ng-src="{{user.picture.large}}"/>
<div class="col-sm-8">
<div ><a ng-click="clickMe(p)" class="clickable"><b>{{user.name.first}} {{user.name.last}}</b></a></div>
<div>{{user.email}}</div>
<div>{{user.location.street}},{{user.location.city}},{{user.location.state}},{{user.location.postcode}}</div>
</div>
</div>
</form>
</div>
</body>
Also check the following link for the demo - https://plnkr.co/edit/J70FKDpdXUtg1AfiVkcz?p=preview
I need to display a particular user's data when we click on the user.
Below is the working example for the same
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link data-require="bootstrap#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script data-require="angular.js#1.6.6" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js" type="text/javascript"></script>
<script>
(function() {
angular.module("testApp", ['ui.bootstrap']).controller('testCtrl', ['$scope', '$http', function($scope, $http) {
$scope.userData = undefined;
$scope.selectedUser = undefined;
$http.get('https://randomuser.me/api/?results=30&nat=US').then(function(response) {
$scope.userData = response.data;
});
$scope.selectUser = function(usr){
$scope.selectedUser=usr;
};
}]);
}());
</script>
<style>
.userInfo{
border: 1px solid #ccc;
margin-top:10px;
padding:5px;
cursor: pointer;
}
.userInfo:hover{
background: #ccc;
}
.profile{
padding-left: 0px;
padding-right: 0px;
}
.ellipsis{
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
</head>
<body ng-app="testApp">
<div ng-controller="testCtrl">
<form name="commonForm">
<div ng-hide="selectedUser">
<div class="col-sm-4 userInfo" ng-repeat="user in userData.results" ng-click="selectUser(user)" >
<img class="col-sm-4 profile" ng-src="{{user.picture.medium}}"/>
<div class="col-sm-8">
<div class="ellipsis"><b>{{user.name.first}} {{user.name.last}}</b></div>
<div class="ellipsis">{{user.email}}</div>
</div>
</div>
</div>
<div ng-show="selectedUser">
<button ng-click="selectedUser = undefined">Go Back</button>
<br />
<br />
<img class="col-sm-4 profile" ng-src="{{selectedUser.picture.large}}"/>
<div class="col-sm-4">
<div class="form-group">
<label for="first">First Name:</label>
<input type="text" class="form-control" id="first" ng-model="selectedUser.name.first">
</div>
<div class="form-group">
<label for="last">Last Name:</label>
<input type="text" class="form-control" id="last" ng-model="selectedUser.name.last">
</div>
<div class="form-group">
<label for="username">Login:</label>
<input type="text" class="form-control" id="username" ng-model="selectedUser.login.username" disabled>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email" ng-model="selectedUser.email">
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="text" class="form-control" id="dob" ng-model="selectedUser.dob">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="nat">Nationality:</label>
<input type="text" class="form-control" id="nat" ng-model="selectedUser.nat">
</div>
</div>
</div>
</form>
</div>
</body>
</html>

ng-init value overridden in angular oi-select mutiple options

I am working on dynamic forms with ng-repeat. I am using the oi-select library for loading my locations. The oi-select box has multi select feature. on my page loading by default, I am loading first option value in that oi-select box.
But I am using a multi select feature if I select any other option than the first option it gets override with that value. Due to this issue, I have to select again that first option. My question is, how can I load my first option value by default into that oi-select?
Afterwards, if I am select any other options it won't override my first value in select box .Here is my plunker link http://plnkr.co/edit/m6Q02dlHLBCMVLRLfioh?p=preview
my HTML code
<body class="container row">
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="user in users">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Location</label>
<oi-select ng-model="user.location" multiple oi-options="v for v in locations" ng-init='initLocation(user)' name="select2" required>
</oi-select>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
</div>
</div>
my js code
var app = angular.module('myApp', ['ngResource', 'oi.select']);
app.controller('myCtrl', function($scope, $timeout) {
$scope.ids = [1, 2, 3];
$scope.users = $scope.ids.map(function(id) {
return {
id: id,
comment: "",
location: ""
};
});
$scope.locations = ['india', 'usa', 'jermany', 'china', 'Dubai'];
$scope.initLocation = (user) => {
$timeout(() => {
user.location = $scope.locations[0];
});
}
$scope.adduser = function() {
var data = $scope.users.map(function(user) {
return {
"userid": user.id,
"manualcomment": user.comment,
"location": user.location
}
});
console.log("data", data)
}
});
If you use multiple attribute, this means the model should be an array and not a string as in your case user.location = $scope.locations[0];, ypu have to change it to location: [] and use push() method to add the initial items to this array;
Using $timeout doesn't make any sense to me;
ngInit adds unnecessary amount of logic into the template, I would prefer avoid using it in you case, just use location: [$scope.locations[0]] in your controller.
Working example:
var app = angular.module('myApp', ['ngResource', 'oi.select']);
app.controller('myCtrl', function($scope, $timeout) {
$scope.ids = [1, 2];
$scope.locations = ['india', 'usa', 'jermany', 'china', 'Dubai'];
$scope.users = $scope.ids.map(function(id) {
return {
id: id,
comment: "",
location: []
};
});
$scope.initLocation = (user, locations) => {
if (!user.location.length) {
user.location.push(locations[0]);
}
}
$scope.adduser = function() {
$scope.users.push({
id: Math.max(...($scope.users.map(u => { return u.id; }))) + 1,
comment: "added from controller",
location: [$scope.locations[2]]
});
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="//rawgit.com/tamtakoe/oi.select/master/dist/select.css" />
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script data-require="angular-resource#1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular-resource.js"></script>
<script src="//rawgit.com/tamtakoe/oi.select/master/dist/select-tpls.js"></script>
<script src="script.js"></script>
</head>
<body class="container row">
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="user in users">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Location</label>
<oi-select ng-model="user.location"
multiple oi-options="v for v in locations" ng-init='initLocation(user, locations)'
name="select2" required>
</oi-select>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</div>
</body>
</html>

how to add dyanamic form fields with unique name in angular js

i have a form in that I added fields dynamically , but when i try to get the unique name it's not working, anyone can help me thanks in advance. Find the below my code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Angular Forms | Form2 </title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="js/angular.js"></script>
<script src="js/jquery-2.0.3.js"></script>
<script src="js/app2.js"></script>
</head>
<body>
<div ng-app="myApp2" ng-controller="myCtrl2">
<div class="container">
<div class="col-sm-9 col-sm-offset-2">
<form name="form1" ng-submit="submitForm2()" enctype="multipart/form-data">
<!--for adding extra fields data-->
{{count}}
<fieldset data-ng-repeat="choice in choices" ng-init="count=0">
<div class="form-group">
<div class="row">
<label class="col-md-2">Skills</label>
<div class="col-md-7">
<input type="text" class="form-control" name="skills" ng-focus="userskills_msg=true" ng-model="user2.skills" placeholder="Enter your skills" />
<p ng-show="errorSkill">{{errorSkill}}</p>
</div>
<div class="col-sm-3 col-md-3"> <span ng-cloak ng-show="userskills_msg"> please choose your location</span> </div>
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
</div>
</div>
</fieldset>
<!--end adding extra fields data-->
<div class="form-group">
<div class="col-md-3"></div>
<div class="col-md-6"> +add another employment<!--<button class="addfields" ng-click="addfields()">Add fields</button>--> </div>
</div>
</div>
</div>
</div>
</body>
</html>
i am initialise a variable using ng-init and i incremented that value in controller value is incrementd but i a not geeting unique names and the file dis not displaying
var sampleApp = angular.module("myApp2", []);
sampleApp.controller("myCtrl2", function ($scope, $http) {
$scope.addfields = function () {
var newItemNo = $scope.choices.length + 1;
$scope.count = newItemNo;
console.log(count);
console.log(newItemNo);
$scope.choices.push({
'id' : 'choice' + newItemNo
});
};
$scope.removeChoice = function () {
var lastItem = $scope.choices.length - 1;
$scope.choices.splice(lastItem);
};
});
This is your code working on plunker.
var sampleApp = angular.module("myApp2", []);
sampleApp.controller("myCtrl2", function ($scope, $http) {
$scope.choices = [];
$scope.count = 0;
$scope.addfields = function () {
var newItemNo = $scope.choices.length + 1;
$scope.count = newItemNo;
console.log($scope.count);
var item = {};
item.id = "choice" + newItemNo;
$scope.choices.push(item);
};
$scope.removeChoice = function () {
var lastItem = $scope.choices.length - 1;
$scope.choices.splice(lastItem);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="controller.js"></script>
</head>
<body>
<div ng-app="myApp2" ng-controller="myCtrl2">
<div class="container">
<div class="col-sm-9 col-sm-offset-2">
<form name="form1" ng-submit="submitForm2()" enctype="multipart/form-data">
{{count}}
<fieldset data-ng-repeat="choice in choices" ng-init="count=0">
<div class="form-group">
<div class="row">
<label class="col-md-2">Skills</label>
<div class="col-md-7">
<input type="text" class="form-control" name="skills" ng-focus="userskills_msg=true" ng-model="user2.skills" placeholder="Enter your skills" />
<p ng-show="errorSkill">{{errorSkill}}</p>
</div>
<div class="col-sm-3 col-md-3"> <span ng-cloak ng-show="userskills_msg"> please choose your location</span> </div>
<button type="button" class="remove" ng-show="$last" ng-click="removeChoice()">Remove Choice</button>
</div>
</div>
</fieldset>
<div class="form-group">
<div class="col-md-3"></div>
<div class="col-md-6">
<button type="button" class="addfields" ng-click="addfields()">Add fields</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
You have forgotten to initialize the necessary variables to function properly
$scope.choices=[];
$scope.count=0;
And some bad references, example console.log(count); Should be console.log ($ scope.count);

Input Fields update AFTER submit button is clicked in angularjs

The input fields should NOT directly update the fields (meaning when I type in the input box you should NOT see the badge field update - only after the Submit button is pressed will the fields populate).
//index.html
<!DOCTYPE html>
<html lang="en" ng-app="MyApp">
<head>
<meta charset="UTF-8">
<title>Name Badge</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body ng-controller="MainController">
<div class="container">
<div class="row">
<div class="col-md-6">
<input class="text" placeholder="First Name" ng-model="fName"><br>
<input class="text" placeholder="Email" ng-model="email"><br>
<input class="text" placeholder="Phone" ng-model="phone">
</div>
<div class="col-md-6">
<input class="text" placeholder="Last Name" ng-model="lName"><br>
<input class="text" placeholder="Place of Birth" ng-model="birth"><br>
<input class="text" placeholder="Favorite Food" ng-model="food">
</div>
</div>
<textarea ng-model="about">Tell us about yourself</textarea><br>
<button class="btn" type="submit" ng-submit="info()">Submit</button>
<br><br>
<br><br><br><br>
<div class="row">
<div class="col-xs-6">
<h3>Name: {{fName}} {{lName}}</h3>
<h3>Place of Birth: {{birth}}</h3>
<h3>Email: {{email}}</h3>
</div>
<div class="col-xs-6">
<h3>Phone: {{phone}}</h3>
<h3>Favorite Food: {{food}}</h3>
</div>
</div>
<textarea>{{about}}</textarea>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<script src="app.js"></script>
</body>
</html>
Here is my app.js
var app = angular.module("MyApp", []);
app.controller("MainController", ['$scope', function ($scope) {
$scope.info = function () {
$scope.fName = fName;
$scope.email = '';
$scope.phone = '';
$scope.lName = '';
$scope.birth = '';
$scope.food = '';
$scope.about = '';
}
}])
Can someone look at my code and help me see what's wrong.
<!DOCTYPE html>
<html lang="en" ng-app="MyApp">
<head>
<meta charset="UTF-8">
<title>Name Badge</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body ng-controller="MainController">
<div class="container">
<div class="row">
<div class="col-md-6">
<input class="text" placeholder="First Name" ng-model="fName"><br>
<input class="text" placeholder="Email" ng-model="email"><br>
<input class="text" placeholder="Phone" ng-model="phone">
</div>
<div class="col-md-6">
<input class="text" placeholder="Last Name" ng-model="lName"><br>
<input class="text" placeholder="Place of Birth" ng-model="birth"><br>
<input class="text" placeholder="Favorite Food" ng-model="food">
</div>
</div>
<textarea ng-model="about">Tell us about yourself</textarea><br>
<button class="btn" type="submit" ng-submit="info()">Submit</button>
<br><br>
<br><br><br><br>
<div class="row">
<div class="col-xs-6">
<h3>Name: {{fName1}} {{lName1}}</h3>
<h3>Place of Birth: {{birth1}}</h3>
<h3>Email: {{email1}}</h3>
</div>
<div class="col-xs-6">
<h3>Phone: {{phone1}}</h3>
<h3>Favorite Food: {{food1}}</h3>
</div>
</div>
<textarea>{{about}}</textarea>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<script src="app.js"></script>
</body>
</html>
js file is
var app = angular.module("MyApp", []);
app.controller("MainController", ['$scope', function ($scope) {
$scope.info = function () {
$scope.fName1 = $scope.fName1;
$scope.email1 = $scope.email;
$scope.phone1 = $scope.phone;
$scope.lName1 = $scope.lName;
$scope.birth1 = $scope.birth;
$scope.food1 = $scope.food;
$scope.about1 = $scope.about;
}
}])

Why does expression in ng-disabled not work?

What does this:
ng-disabled="login == ''"
not disable the button when the input field login is empty?
<html ng-app="mainApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" rel="stylesheet" />
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.js"></script>
</head>
<body ng-controller="mainController">
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-heading">
LOGIN
</div>
<div class="panel-body">
<form>
<div class="form-group">
<label for="login">Login</label>
<input type="text" class="form-control" id="login" ng-model="login">
</div>
<div class="form-group">
<label for="inputPassword">Passowrd</label>
<input type="password" class="form-control" id="password">
</div>
<button type="submit" ng-disabled="login == ''" class="btn btn-primary">Login</button>
</form>
</div>
</div>
</div>
<script>
var mainApp = angular.module('mainApp', []);
mainApp.controller('mainController', function ($scope) {
});
</script>
</body>
</html>
Create a form object in your controller which would hold each model property/field, and then check if the field (login) equates and empty string.
...
<input type="text" class="form-control" id="login" ng-model="form.login">
...
<button type="submit" ng-disabled="form.login === ''" class="btn btn-primary">Login</button>
....
Controller
mainApp.controller('mainController', function ($scope) {
$scope.form = {
login: ''
}
});
JSFIDDLE

Resources