【问题标题】:Adding function to Json Array in AngularJS在 AngularJS 中向 Json 数组添加函数
【发布时间】:2015-04-01 05:24:08
【问题描述】:

我有这个从 webapi 返回的 JSON 对象,

[{name:John,val1:10,val2:20,val3:0},
{name:Jane,val1:50,val2:200,val3:0}]

我将此数组存储在“$scope.dtArray”中,该数组使用 ng-repeat 绑定到 UI(文本框)。在绑定发生之前,我想分配一个函数来添加值,如下所示

this.val3 = function() {return Number(this.val1) + Number(this.val2) };

对于数组中的每个对象。因此,当用户更改 val1 和 val2 文本框时,val3 的值会自动更改。

以下是 UI 标记...

<div ng-repeat="cnt in dtArray track by $index">
    <table style="border-style: solid;">
        <tr>
            <td>
                <input type="text" ng-model="cnt.name">
                <input type="text" ng-model="cnt.val1">
                <input type="text" ng-model="cnt.val2">
                <input type="text" ng-model="cnt.val3()">
            </td>
        </tr>
    </table>
</div>

函数在 val1 或 val2 中的值变化时没有被调用。

任何帮助将不胜感激。

谢谢。

【问题讨论】:

  • 您必须在您的服务中添加该功能,例如您将 json 分配给 angular 中的数据对象的位置。
  • 能否分享您的完整代码

标签: arrays json angularjs


【解决方案1】:

试试下面的 html 代码而不是你的代码

<div ng-repeat="cnt in dtArray track by $index">
    <table style="border-style: solid;">
        <tr>
            <td>
                <input type="text" ng-model="cnt.name">
                <input type="text" ng-model="cnt.val1">
                <input type="text" ng-model="cnt.val2">
                <input type="text" ng-init="cnt.val3=val3(this)" ng-model="cnt.val3">
            </td>
        </tr>
    </table>
</div>

你的val3函数也应该被$scope.functionName()使用

喜欢:

$scope.val3

试试下面的代码而不是你的代码

$scope.val3 = function(context) {return Number(context.val1) + Number(context.val2) };

【讨论】:

  • 将函数绑定到输入 ng-model 是没有意义的,我很惊讶 Angular 甚至可以容忍这种情况(如果可以的话)。
  • 输入值可以使用ng-value="cnt.val3=val3(this)" 但是你为什么通过这个,我很想知道它
  • 我的回答中没有使用ng-value
  • 感谢您的意见,
  • 这仍然行不通:val3 被初始化为正确的值,但在用户编辑 val1 和 val2 时没有更新。
【解决方案2】:

您仍希望 val3 成为可编辑输入吗?你可以这样做:

<input type="text" ng-model="cnt.name">
<input type="text" ng-model="cnt.val1">
<input type="text" ng-model="cnt.val2">
<input type="text" ng-model="cnt.val3">

在你的控制器中

$scope.$watch('(cnt.val1 || 0) + (cnt.val2 || 0)', function(total) {
  $scope.cnt.val3 = total;
});

这样 val3 会在 val1 或 val2 更改时更新,但也可以自行编辑。

【讨论】:

  • @RameshRajendran 抱歉,什么不完全有效?如果你清除谁,val3 还是 val1/val2?我没有检查值何时确实为空,我已经用它编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 2011-09-17
  • 2021-06-01
  • 1970-01-01
  • 2011-11-05
  • 1970-01-01
相关资源
最近更新 更多