AngularJS REST 请求更新范围变量的值,但更改在前端不可见

AngularJS REST request updates a scope variable's value but the change not visible on front-end

我目前正在使用 AngularJS 1.8。我有一个带有按钮的视图。单击按钮后,会出现一个模态视图,我使用 ng-init="set_my_url()" 调用我的控制器函数,该函数发送一个 REST 请求,其中 returns 一个 URL 地址。

在我从 REST 请求中得到这个 URL 地址后,我将它的值分配给一个范围变量 $scope.my_url

问题是当我在REST请求完成后调用console.log($scope.my_url)时,我得到了一个有效的URL地址,但是$scope.my_url的值在前面没有改变-结束视图 - 在前端,变量 $scope.my_url 为 EMPTY。我不知道为什么。我该如何解决?

/modal.html(模态视图):

<div class="modal" ng-controller="link_modal">
    <table>
        <tr>
            <td>
                <div class="modal-body">
                    <div class="fullHeight">
                        <div class="inner">
                            <table>
                                <tbody>
                                    <tr ng-init="set_my_url()">
                                        <td colspan="2">
                                            <?= t('Your URL address:');?>:
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2">
                                            <input type="text" ng-value="my_url" />  
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </td>
        </tr>
    </table>
</div>

/js/controllers/modal_link.js(控制器)

app.controller('modal_link', function($scope, $element) {

    $scope.set_my_url = function() {

            var r = new Rest(user, "/my_api_endpoint", false);

            r.ignore401 = true;

            r.always(function(response) {
                
                $scope.url = response.url;

                console.log($scope.url);    // This value is correctly updated but the change is not visible on the front-end

            });

            r.post({
                data : JSON.stringify($scope.data)
            });
    };

});

您将值设置为 $scope.url,而不是 $scope.my_url。此外,您可能希望为简单数据类型(字符串、数字等)添加一个视图模型,因为如果没有它,双向绑定可能会很时髦。

app.controller('modal_link', function($scope, $element) {
    $scope.vm = {
        url = '';
    }

    $scope.set_my_url = function() {
        // ... some code
        
        r.always(function(response) {                
            $scope.vm.url = response.url;
        });

    // other code
    };
});

<td colspan="2">
    <input type="text" ng-value="vm.url" />  
</td>