在AngularJS中,如何在模型更新后更新视图

In AngularJS, How to update view after model is updated?

本文关键字:更新 新视图 模型 AngularJS      更新时间:2023-09-26

在下面的代码段中,两个变量$scope.recordList &$scope.recordList2有完全相同的值。$scope.recordList2已设置为静态值,$scope.recordList在收到服务器响应后更新。语句$scope.recordList &$scope.recordList2呈现相同的值,$scope.recordList在收到响应后呈现。

最后有两个智能表(https://github.com/lorenzofox3/Smart-Table)。$scope.recordList2基表按预期工作。基于$scope.recordList的表不能正常工作

在AngularJS中,如何在模型更新后更新视图?

<div ng-app="smartTableApp" ng-controller="smartTableController">
    <script>  
        angular.module('smartTableApp', [ 'AngularJSRemoting','smartTableApp.controllers', 'smartTable.table']);
        angular.module('smartTableApp.controllers', []).controller('smartTableController', function($scope, jsr) {
        jsr.Call('appController.query', '{!soql}').then(function(response) {
            $scope.recordList = response;
            //$scope.$apply() ; uncommenting this gives "$digest already in progress" error
        },function(err){
            console.log(err);
        });
        $scope.recordList2=[{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6yAAA"},"Name":"Stella Pavlova","Phone":"(212) 842-5500","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6yAAA"},{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6zAAA"},"Name":"Lauren Boyle","Phone":"(212) 842-5500","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6zAAA"},{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt70AAA"},"Name":"Babara Levy","Phone":"(503) 421-7800","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt70AAA"},{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt71AAA"},"Name":"Josh Davis","Phone":"(503) 421-7800","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt71AAA"},{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt72AAA"},"Name":"Jane Grey","Phone":"(520) 773-9050","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt72AAA"}] ;
    });
    </script>   
    <br/>----------recordList----------<br/><!-- Shows expected values -->
    {{recordList}}
    <br/>----------recordList2----------<br/><!-- Shows expected values -->
    {{recordList2}}
    <br/><br/>
    <smart-table rows="recordList" ></smart-table><br/><br/><!-- table is NOT rendered -->
    <smart-table rows="recordList2" ></smart-table><br/><br/><!-- table is rendered -->       
</div>

问题不在于Angular没有更新视图。实际上,您可以在代码示例中指出它正在更新它:

<br/>----------recordList----------<br/><!-- Shows expected values -->
{{recordList}}

我没有Smart-Table的经验,但我确实在GitHub上发现了这个问题,它描述了一个类似的问题。该模块的作者确实回复并建议初始化表仅列配置,以避免问题(他描述为一个bug)。

因此,如果您在查询之前知道数据的结构,那么您应该使用列数据初始化您的表。