我有一个在我的html代码中运行的函数,我在调用该函数时无法使用控制器中的输出执行更多操作。
首先,这是我的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);
我的HTML如下:
<!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>
我面临的问题是当我在控制器中调用$ scope.discprice()时,它会给我一个未定义的输出。任何提示都将不胜感激。
这是我的代码的一部分: http://plnkr.co/edit/bLqAdpGOwMsNThK3Ei6s?p=preview
答案 0 :(得分:1)
据我所知,您只能绑定模型元素,而不是变量,最好的方法是将返回值作为模型元素并将函数加载为默认值并映射模型元素以进行绑定