angularjs - 从 ng-value 指令更新 ng-model

标签 angularjs angular-ngmodel

我遇到的情况是,表单中有几个只读字段,就像其他字段一样来显示问题

您可以看到最后两个输入是只读,它们是计算输入,其中总借记是通过$scope上的totalDebit函数计算的,并且总积分由 $scope 上的 totalCredit() 函数计算。问题是输入仅反射(reflect) ng-model 值,该值对于两个输入均为零,并且不从计算函数中获取值。简化的 Controller 是

app.controller('myController', ['$scope' ,function($scope){
$scope.credit = 0;
$scope.debit = 0;
$scope.debitSum = 0;
$scope.creditSum = 0;

$scope.totalCredit = function(){
   return $scope.credit + 200; //just to show that it is calculated field
}

$scope.totalDebit = function(){
   return $scope.debit + 200; //just to show that it is calculated field
}

}]);

如果您从只读输入中删除 ng-model 指令,它们将分别采用 totalDebittotalCredit 函数的值。但我希望它们使用函数中的值,并更新 totalDebittotalCredit$scope 属性。这是plunker对于此代码

最佳答案

不应该在这里回答(为什么 ng-value 没有达到预期的效果):

ngValue

Binds the given expression to the value of <option> or input[radio], so that when the element is selected, the ngModel of that element is set to the bound value.

这不是我们的情况......

Because, the ngValue is triggered on CHANGE. When we select radio or some option in the <select>

所以,ng-value在这种情况下不是正确的设置。

我们可以这样调整:

<input name="totalDebit" value="{{totalDebit()}}" readonly="" />
<input name="totalCredit" value="{{totalCredit()}}" readonly="" />

参见updated plunker

关于angularjs - 从 ng-value 指令更新 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27675874/

相关文章:

javascript - 作为 ng-model 属性名称的 Angular JS 对象

javascript - angular js $location.path 回调

javascript - 如何从 angular.js 中的服务进行 $rootScope.$broadcast

javascript - 在服务中无法访问 Angular ngResource 响应对象

angular - 显示 mat-select 的 ngModel 值

javascript - 如何将 ng-model 添加到运行时创建的 html 对象

javascript - 触发 ng-model.$formatters 以编程方式运行

javascript - ng-binding 不工作但 ng-model 工作

javascript - Angular/Bootstrap - 模式不显示(仅背景变化)

iphone - Ionic 和 sails.js(后端)测试