javascript - ng-repeat 在更新 $scope 后不更新信息

标签 javascript angularjs angularjs-ng-repeat

我有一个ng-repeat,它创建一个包含一些起始数据的表单。然后,用户可以自由修改所述数据,并且更改应显示在表单中。在此之前,用户提交的数据由另一个函数进行清理,该函数由按钮上的 ng-click 调用。

一切都在后台运行良好(我检查了我的 $scope.some_arrayng-repeat 从中获取数据,并且新数据位于正确的位置)但页面上没有任何反应。

元素:

<li ng-repeat="field in some_array" id="field-{{$index}}">
            <div class="{{field.field_color}}">
                <button type="button" ng-click="save_field($index)">done</button>
                {{field.nice_name}}
            </div>
            <div id="field-input-{{$index}}">
                <input type="text" id="{{field.tag}}" value="{{field.content}}">
                <label  for="{{field.tag}}">{{field.nice_name}}</label>
            </div>
  </li>

save_field代码:

$scope.save_field = function (index) {
        console.log($scope.some_array[index]["content"])
        var value = $("#field-" + index).children("div").children("input").val()
        var name = $scope.some_array[index]["name"]
        var clean_value = my_clean(value)
        if (norm_value === "") {
            return
        }
        $scope.some_array[index]["content"] = clean_value
        console.log($scope.some_array[index]["content"])
    }

在控制台上我看到:

10.03.16
10/03/16

这是正确的,但在表单中我只看到10.03.16。我已经尝试将 $timeout(function(){$scope.$apply()}) 作为函数的最后一行,但输出仍然相同。

最佳答案

如果您想将变量绑定(bind)到它,则不应使用这样的输入。摘要循环将刷新该值,但不会明显更新,因为这不是 html native 行为。

改用 ng-model,它将按预期更新输入的 View 值:

<input type="text" id="{{field.tag}}" ng-model="field.content">

还使用 ng-model 当用户修改输入时,您的变量将被更新,因此您可以在 save_field 函数中检索它以更轻松地进行一些处理,而无需 jQuery:

$scope.save_field = function (index) {
    if (norm_value === "") {
      return;
    }
    $scope.some_array[index]["content"] = my_clean($scope.some_array[index]["content"]);
};

更多信息:https://docs.angularjs.org/api/ng/directive/ngModel

关于javascript - ng-repeat 在更新 $scope 后不更新信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37239176/

相关文章:

javascript - 构建并运行后,是否可以在浏览器中查看以 Angular 声明的 secret 变量?

java - 如何在网页中调用嵌入式java函数

javascript - 如何将事件数据从下拉列表传递到按钮 Angular 2

javascript - 在调用 api 函数之前等待内部指令编译

javascript - AngularJS 将类添加到 <td> 中,该类由 ngRepeat 从数据库动态生成

javascript - Angularjs 从 Json 对象中删除子对象

javascript - 使用 ng-repeat 和条件语句填充表格

angularjs ng-model 选择未正确更新

javascript - AngularJS:ng-repeat并不总是显示数据

javascript - 从 ng-repeat 填充卡片