题
我试图在Angular中构建一个简单的计算器,如果我愿意,我可以复盖总计。我有这部分工作,但是当我回到一个或两个字段中输入一个数字时,总计不会在字段中更新。
这是我的jsfiddle http://jsfiddle.net/YUza7/2/
表格
<div ng-app>
<h2>Calculate</h2>
<div ng-controller="TodoCtrl">
<form>
<li>Number 1: <input type="text" ng-model="one">
<li>Number 2: <input type="text" ng-model="two">
<li>Total <input type="text" value="{{total()}}">
{{total()}}
</form>
</div>
</div>
的javascript
function TodoCtrl($scope) {
$scope.total = function(){
return $scope.one * $scope.two;
};
}
解决方案
您可以为输入字段添加ng-change
指令。看看docs 示例
其他提示
我猜当你在totals字段中输入一个值时,值表达式会以某种方式被复盖。
但是,您可以采取替代方法:为总价值创建一个字段,并在任何时候创建一个字段 one
或 two
更改会更新该字段。
<li>Total <input type="text" ng-model="total">{{total}}</li>
并更改javascript:
function TodoCtrl($scope) {
$scope.$watch('one * two', function (value) {
$scope.total = value;
});
}
示例小提琴 这里.
我写了一个指令,你可以用来将ng-model绑定到您想要的任何表达式。每当表达式更改时,模型都设置为新值。
module.directive('boundModel', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
var boundModel$watcher = scope.$watch(attrs.boundModel, function(newValue, oldValue) {
if(newValue != oldValue) {
ngModel.$setViewValue(newValue);
ngModel.$render();
}
});
// When $destroy is fired stop watching the change.
// If you don't, and you come back on your state
// you'll have two watcher watching the same properties
scope.$on('$destroy', function() {
boundModel$watcher();
});
}
});
.
您可以在这样的模板中使用它:
<li>Total<input type="text" ng-model="total" bound-model="one * two"></li>
. 您只需要纠正HTML 的格式
<form>
<li>Number 1: <input type="text" ng-model="one"/> </li>
<li>Number 2: <input type="text" ng-model="two"/> </li>
<li>Total <input type="text" value="{{total()}}"/> </li>
{{total()}}
</form>
.
创建一个指令并将手表放在上面。
app.directive("myApp", function(){
link:function(scope){
function:getTotal(){
..do your maths here
}
scope.$watch('one', getTotals());
scope.$watch('two', getTotals());
}
.
})
不隶属于 StackOverflow