Reputation: 245
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="[email protected]" 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
Upvotes: 1
Views: 173
Reputation: 663
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
Upvotes: 1